From 6b55db452cc8444d5d9699f81d477377cbb52519 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 17 Aug 2018 08:48:25 -0700 Subject: [PATCH] Update LKG and remove newly unnecessary non-null assertions --- lib/de/diagnosticMessages.generated.json | 4 +- lib/enu/diagnosticMessages.generated.json.lcg | 162 +- lib/lib.dom.d.ts | 5543 ++-- lib/lib.dom.iterable.d.ts | 36 +- lib/lib.es5.d.ts | 8 +- lib/lib.webworker.d.ts | 548 +- lib/protocol.d.ts | 27 +- lib/pt-br/diagnosticMessages.generated.json | 2 +- lib/tsc.js | 4099 ++- lib/tsserver.js | 7882 +++-- lib/tsserverlibrary.d.ts | 8531 +----- lib/tsserverlibrary.js | 25186 +++++++++------- lib/typescript.d.ts | 182 +- lib/typescript.js | 7113 +++-- lib/typescriptServices.d.ts | 179 +- lib/typescriptServices.js | 7113 +++-- lib/typingsInstaller.js | 4673 +-- src/compiler/checker.ts | 2 +- src/services/jsDoc.ts | 2 +- 19 files changed, 39657 insertions(+), 31635 deletions(-) diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index afb8baa15b678..795136609dc0a 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -49,8 +49,8 @@ "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Eine Namespacedeklaration darf nicht vor der Klasse oder Funktion positioniert werden, mit der sie zusammengeführt wird.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Eine Namespacedeklaration ist nur in einem Namespace oder Modul zulässig.", "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Ein Import im Namespacestil kann nicht aufgerufen oder erstellt werden und verursacht zur Laufzeit einen Fehler.", - "A_non_dry_build_would_build_project_0_6357": "Bei einem Build mit dem Flag \"-dry\" würde das Projekt \"{0}\" erstellt.", - "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Bei einem Build mit dem Flag \"-dry\" würden die folgenden Dateien gelöscht: {0}", + "A_non_dry_build_would_build_project_0_6357": "Bei einem Build ohne das Flag \"-dry\" würde das Projekt \"{0}\" erstellt.", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Bei einem Build ohne das Flag \"-dry\" würden die folgenden Dateien gelöscht: {0}", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Ein Parameterinitialisierer ist nur in einer Funktions- oder Konstruktorimplementierung zulässig.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Eine Parametereigenschaft darf nicht mithilfe eines rest-Parameters deklariert werden.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Eine Parametereigenschaft ist nur in einer Konstruktorimplementierung zulässig.", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 185925b4fae37..2c93bcf114d47 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -267,6 +267,12 @@ + + + + + + @@ -645,6 +651,12 @@ + + + + + + @@ -777,6 +789,12 @@ + + + + + + @@ -849,6 +867,12 @@ + + + + + + @@ -921,6 +945,12 @@ + + + + + + @@ -1341,6 +1371,12 @@ + + + + + + @@ -1749,6 +1785,12 @@ + + + + + + @@ -1767,6 +1809,12 @@ + + + + + + @@ -1821,6 +1869,12 @@ + + + + + + @@ -2855,7 +2909,7 @@ - + @@ -2895,6 +2949,12 @@ + + + + + + @@ -2925,6 +2985,12 @@ + + + + + + @@ -3531,6 +3597,12 @@ + + + + + + @@ -3615,6 +3687,12 @@ + + + + + + @@ -3831,6 +3909,12 @@ + + + + + + @@ -4245,6 +4329,12 @@ + + + + + + @@ -4521,6 +4611,18 @@ + + + + + + + + + + + + @@ -4539,12 +4641,24 @@ + + + + + + + + + + + + @@ -4671,6 +4785,12 @@ + + + + + + @@ -5169,6 +5289,12 @@ + + + + + + @@ -5409,6 +5535,12 @@ + + + + + + @@ -5451,6 +5583,12 @@ + + + + + + @@ -5475,9 +5613,9 @@ - + - + @@ -5499,12 +5637,6 @@ - - - - - - @@ -6141,6 +6273,12 @@ + + + + + + @@ -6279,12 +6417,6 @@ - - - - - - diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 920c0ad2dae17..f08e5d556776e 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -91,6 +91,10 @@ interface AssertionOptions { timeoutSeconds?: number; } +interface AssignedNodesOptions { + flatten?: boolean; +} + interface AudioBufferOptions { length: number; numberOfChannels?: number; @@ -172,6 +176,10 @@ interface CacheQueryOptions { ignoreVary?: boolean; } +interface CanvasRenderingContext2DSettings { + alpha?: boolean; +} + interface ChannelMergerOptions extends AudioNodeOptions { numberOfInputs?: number; } @@ -355,6 +363,10 @@ interface DoubleRange { min?: number; } +interface DragEventInit extends MouseEventInit { + dataTransfer?: DataTransfer | null; +} + interface DynamicsCompressorOptions extends AudioNodeOptions { attack?: number; knee?: number; @@ -364,15 +376,15 @@ interface DynamicsCompressorOptions extends AudioNodeOptions { } interface EcKeyAlgorithm extends KeyAlgorithm { - namedCurve: string; + namedCurve: NamedCurve; } interface EcKeyGenParams extends Algorithm { - namedCurve: string; + namedCurve: NamedCurve; } interface EcKeyImportParams extends Algorithm { - namedCurve: string; + namedCurve: NamedCurve; } interface EcdhKeyDeriveParams extends Algorithm { @@ -380,7 +392,7 @@ interface EcdhKeyDeriveParams extends Algorithm { } interface EcdsaParams extends Algorithm { - hash: string | Algorithm; + hash: HashAlgorithmIdentifier; } interface EffectTiming { @@ -394,6 +406,10 @@ interface EffectTiming { iterations?: number; } +interface ElementDefinitionOptions { + extends?: string; +} + interface ErrorEventInit extends EventInit { colno?: number; error?: any; @@ -434,25 +450,6 @@ interface ExceptionInformation { domain?: string | null; } -interface ExtendableEventInit extends EventInit { -} - -interface ExtendableMessageEventInit extends ExtendableEventInit { - data?: any; - lastEventId?: string; - origin?: string; - ports?: MessagePort[]; - source?: object | ServiceWorker | MessagePort; -} - -interface FetchEventInit extends ExtendableEventInit { - clientId?: string; - preloadResponse: Promise; - request: Request; - resultingClientId?: string; - targetClientId?: string; -} - interface FilePropertyBag extends BlobPropertyBag { lastModified?: number; } @@ -476,6 +473,10 @@ interface FocusNavigationOrigin { originWidth?: number; } +interface FocusOptions { + preventScroll?: boolean; +} + interface GainOptions extends AudioNodeOptions { gain?: number; } @@ -488,19 +489,23 @@ interface GetNotificationOptions { tag?: string; } +interface GetRootNodeOptions { + composed?: boolean; +} + interface HashChangeEventInit extends EventInit { newURL?: string; oldURL?: string; } interface HkdfParams extends Algorithm { - hash: string | Algorithm; + hash: HashAlgorithmIdentifier; info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; } interface HmacImportParams extends Algorithm { - hash: string | Algorithm; + hash: HashAlgorithmIdentifier; length?: number; } @@ -510,7 +515,7 @@ interface HmacKeyAlgorithm extends KeyAlgorithm { } interface HmacKeyGenParams extends Algorithm { - hash: string | Algorithm; + hash: HashAlgorithmIdentifier; length?: number; } @@ -521,7 +526,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: string | string[]; + keyPath?: string | string[] | null; } interface IDBVersionChangeEventInit extends EventInit { @@ -601,308 +606,6 @@ interface LongRange { min?: number; } -interface MSAccountInfo { - accountImageUri?: string; - accountName?: string; - rpDisplayName: string; - userDisplayName: string; - userId?: string; -} - -interface MSAudioLocalClientEvent extends MSLocalClientEventBase { - cpuInsufficientEventRatio?: number; - deviceCaptureNotFunctioningEventRatio?: number; - deviceClippingEventRatio?: number; - deviceEchoEventRatio?: number; - deviceGlitchesEventRatio?: number; - deviceHalfDuplexAECEventRatio?: number; - deviceHowlingEventCount?: number; - deviceLowSNREventRatio?: number; - deviceLowSpeechLevelEventRatio?: number; - deviceMultipleEndpointsEventCount?: number; - deviceNearEndToEchoRatioEventRatio?: number; - deviceRenderMuteEventRatio?: number; - deviceRenderNotFunctioningEventRatio?: number; - deviceRenderZeroVolumeEventRatio?: number; - networkDelayEventRatio?: number; - networkSendQualityEventRatio?: number; -} - -interface MSAudioRecvPayload extends MSPayloadBase { - burstLossLength1?: number; - burstLossLength2?: number; - burstLossLength3?: number; - burstLossLength4?: number; - burstLossLength5?: number; - burstLossLength6?: number; - burstLossLength7?: number; - burstLossLength8OrHigher?: number; - fecRecvDistance1?: number; - fecRecvDistance2?: number; - fecRecvDistance3?: number; - packetReorderDepthAvg?: number; - packetReorderDepthMax?: number; - packetReorderRatio?: number; - ratioCompressedSamplesAvg?: number; - ratioConcealedSamplesAvg?: number; - ratioStretchedSamplesAvg?: number; - samplingRate?: number; - signal?: MSAudioRecvSignal; -} - -interface MSAudioRecvSignal { - initialSignalLevelRMS?: number; - recvNoiseLevelCh1?: number; - recvSignalLevelCh1?: number; - renderLoopbackSignalLevel?: number; - renderNoiseLevel?: number; - renderSignalLevel?: number; -} - -interface MSAudioSendPayload extends MSPayloadBase { - audioFECUsed?: boolean; - samplingRate?: number; - sendMutePercent?: number; - signal?: MSAudioSendSignal; -} - -interface MSAudioSendSignal { - noiseLevel?: number; - sendNoiseLevelCh1?: number; - sendSignalLevelCh1?: number; -} - -interface MSConnectivity { - iceType?: MSIceType; - iceWarningFlags?: MSIceWarningFlags; - relayAddress?: MSRelayAddress; -} - -interface MSCredentialFilter { - accept?: MSCredentialSpec[]; -} - -interface MSCredentialParameters { - type?: MSCredentialType; -} - -interface MSCredentialSpec { - id?: string; - type: MSCredentialType; -} - -interface MSDCCEventInit extends EventInit { - maxFr?: number; - maxFs?: number; -} - -interface MSDSHEventInit extends EventInit { - sources?: number[]; - timestamp?: number; -} - -interface MSDelay { - roundTrip?: number; - roundTripMax?: number; -} - -interface MSDescription extends RTCStats { - connectivity?: MSConnectivity; - deviceDevName?: string; - localAddr?: MSIPAddressInfo; - networkconnectivity?: MSNetworkConnectivityInfo; - reflexiveLocalIPAddr?: MSIPAddressInfo; - remoteAddr?: MSIPAddressInfo; - transport?: RTCIceProtocol; -} - -interface MSFIDOCredentialParameters extends MSCredentialParameters { - algorithm?: string | Algorithm; - authenticators?: string[]; -} - -interface MSIPAddressInfo { - ipAddr?: string; - manufacturerMacAddrMask?: string; - port?: number; -} - -interface MSIceWarningFlags { - allocationMessageIntegrityFailed?: boolean; - alternateServerReceived?: boolean; - connCheckMessageIntegrityFailed?: boolean; - connCheckOtherError?: boolean; - fipsAllocationFailure?: boolean; - multipleRelayServersAttempted?: boolean; - noRelayServersConfigured?: boolean; - portRangeExhausted?: boolean; - pseudoTLSFailure?: boolean; - tcpNatConnectivityFailed?: boolean; - tcpRelayConnectivityFailed?: boolean; - turnAuthUnknownUsernameError?: boolean; - turnTcpAllocateFailed?: boolean; - turnTcpSendFailed?: boolean; - turnTcpTimedOut?: boolean; - turnTurnTcpConnectivityFailed?: boolean; - turnUdpAllocateFailed?: boolean; - turnUdpSendFailed?: boolean; - udpLocalConnectivityFailed?: boolean; - udpNatConnectivityFailed?: boolean; - udpRelayConnectivityFailed?: boolean; - useCandidateChecksFailed?: boolean; -} - -interface MSJitter { - interArrival?: number; - interArrivalMax?: number; - interArrivalSD?: number; -} - -interface MSLocalClientEventBase extends RTCStats { - networkBandwidthLowEventRatio?: number; - networkReceiveQualityEventRatio?: number; -} - -interface MSNetwork extends RTCStats { - delay?: MSDelay; - jitter?: MSJitter; - packetLoss?: MSPacketLoss; - utilization?: MSUtilization; -} - -interface MSNetworkConnectivityInfo { - linkspeed?: number; - networkConnectionDetails?: string; - vpn?: boolean; -} - -interface MSNetworkInterfaceType { - interfaceTypeEthernet?: boolean; - interfaceTypePPP?: boolean; - interfaceTypeTunnel?: boolean; - interfaceTypeWWAN?: boolean; - interfaceTypeWireless?: boolean; -} - -interface MSOutboundNetwork extends MSNetwork { - appliedBandwidthLimit?: number; -} - -interface MSPacketLoss { - lossRate?: number; - lossRateMax?: number; -} - -interface MSPayloadBase extends RTCStats { - payloadDescription?: string; -} - -interface MSPortRange { - max?: number; - min?: number; -} - -interface MSRelayAddress { - port?: number; - relayAddress?: string; -} - -interface MSSignatureParameters { - userPrompt?: string; -} - -interface MSTransportDiagnosticsStats extends RTCStats { - allocationTimeInMs?: number; - baseAddress?: string; - baseInterface?: MSNetworkInterfaceType; - iceRole?: RTCIceRole; - iceWarningFlags?: MSIceWarningFlags; - interfaces?: MSNetworkInterfaceType; - localAddrType?: MSIceAddrType; - localAddress?: string; - localInterface?: MSNetworkInterfaceType; - localMR?: string; - localMRTCPPort?: number; - localSite?: string; - msRtcEngineVersion?: string; - networkName?: string; - numConsentReqReceived?: number; - numConsentReqSent?: number; - numConsentRespReceived?: number; - numConsentRespSent?: number; - portRangeMax?: number; - portRangeMin?: number; - protocol?: RTCIceProtocol; - remoteAddrType?: MSIceAddrType; - remoteAddress?: string; - remoteMR?: string; - remoteMRTCPPort?: number; - remoteSite?: string; - rtpRtcpMux?: boolean; - stunVer?: number; -} - -interface MSUtilization { - bandwidthEstimation?: number; - bandwidthEstimationAvg?: number; - bandwidthEstimationMax?: number; - bandwidthEstimationMin?: number; - bandwidthEstimationStdDev?: number; - packets?: number; -} - -interface MSVideoPayload extends MSPayloadBase { - durationSeconds?: number; - resolution?: string; - videoBitRateAvg?: number; - videoBitRateMax?: number; - videoFrameRateAvg?: number; - videoPacketLossRate?: number; -} - -interface MSVideoRecvPayload extends MSVideoPayload { - lowBitRateCallPercent?: number; - lowFrameRateCallPercent?: number; - recvBitRateAverage?: number; - recvBitRateMaximum?: number; - recvCodecType?: string; - recvFpsHarmonicAverage?: number; - recvFrameRateAverage?: number; - recvNumResSwitches?: number; - recvReorderBufferMaxSuccessfullyOrderedExtent?: number; - recvReorderBufferMaxSuccessfullyOrderedLateTime?: number; - recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number; - recvReorderBufferPacketsDroppedDueToTimeout?: number; - recvReorderBufferReorderedPackets?: number; - recvResolutionHeight?: number; - recvResolutionWidth?: number; - recvVideoStreamsMax?: number; - recvVideoStreamsMin?: number; - recvVideoStreamsMode?: number; - reorderBufferTotalPackets?: number; - videoFrameLossRate?: number; - videoPostFECPLR?: number; - videoResolutions?: MSVideoResolutionDistribution; -} - -interface MSVideoResolutionDistribution { - cifQuality?: number; - h1080Quality?: number; - h1440Quality?: number; - h2160Quality?: number; - h720Quality?: number; - vgaQuality?: number; -} - -interface MSVideoSendPayload extends MSVideoPayload { - sendBitRateAverage?: number; - sendBitRateMaximum?: number; - sendFrameRateAverage?: number; - sendResolutionHeight?: number; - sendResolutionWidth?: number; - sendVideoStreamsMax?: number; -} - interface MediaElementAudioSourceOptions { mediaElement: HTMLMediaElement; } @@ -930,6 +633,11 @@ interface MediaKeySystemMediaCapability { robustness?: string; } +interface MediaQueryListEventInit extends EventInit { + matches?: boolean; + media?: string; +} + interface MediaStreamAudioSourceOptions { mediaStream: MediaStream; } @@ -1021,12 +729,11 @@ interface MediaTrackSupportedConstraints { } interface MessageEventInit extends EventInit { - channel?: string; data?: any; lastEventId?: string; origin?: string; ports?: MessagePort[]; - source?: Window | null; + source?: MessageEventSource | null; } interface MouseEventInit extends EventModifierInit { @@ -1039,15 +746,6 @@ interface MouseEventInit extends EventModifierInit { screenY?: number; } -interface MsZoomToOptions { - animate?: string; - contentX?: number; - contentY?: number; - scaleFactor?: number; - viewportX?: string | null; - viewportY?: string | null; -} - interface MutationObserverInit { attributeFilter?: string[]; attributeOldValue?: boolean; @@ -1069,11 +767,6 @@ interface NotificationAction { title: string; } -interface NotificationEventInit extends ExtendableEventInit { - action?: string; - notification: Notification; -} - interface NotificationOptions { actions?: NotificationAction[]; badge?: string; @@ -1195,7 +888,7 @@ interface PaymentShippingOption { } interface Pbkdf2Params extends Algorithm { - hash: string | Algorithm; + hash: HashAlgorithmIdentifier; iterations: number; salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; } @@ -1254,15 +947,6 @@ interface PropertyIndexedKeyframes extends Record any) | null; addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -1972,6 +1641,19 @@ declare var AbortSignal: { new(): AbortSignal; }; +interface AbstractRange { + readonly collapsed: boolean; + readonly endContainer: Node; + readonly endOffset: number; + readonly startContainer: Node; + readonly startOffset: number; +} + +declare var AbstractRange: { + prototype: AbstractRange; + new(): AbstractRange; +}; + interface AbstractWorkerEventMap { "error": ErrorEvent; } @@ -2102,17 +1784,29 @@ interface ApplicationCacheEventMap { } interface ApplicationCache extends EventTarget { + /** @deprecated */ oncached: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ onchecking: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ ondownloading: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ onerror: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ onobsolete: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null; + /** @deprecated */ onupdateready: ((this: ApplicationCache, ev: Event) => any) | null; + /** @deprecated */ readonly status: number; + /** @deprecated */ abort(): void; + /** @deprecated */ swapCache(): void; + /** @deprecated */ update(): void; readonly CHECKING: number; readonly DOWNLOADING: number; @@ -2137,12 +1831,10 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; -interface AssignedNodesOptions { - flatten?: boolean; -} - interface Attr extends Node { + readonly localName: string; readonly name: string; + readonly namespaceURI: string | null; readonly ownerElement: Element | null; readonly prefix: string | null; readonly specified: boolean; @@ -2426,7 +2118,7 @@ interface BaseAudioContext extends EventTarget { createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; createStereoPanner(): StereoPannerNode; createWaveShaper(): WaveShaperNode; - decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise; + decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback | null, errorCallback?: DecodeErrorCallback | null): Promise; resume(): Promise; addEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -3177,14 +2869,51 @@ declare var CacheStorage: { new(): CacheStorage; }; -interface Canvas2DContextAttributes { - alpha?: boolean; - storage?: boolean; - willReadFrequently?: boolean; - [attribute: string]: boolean | string | undefined; +interface CanvasCompositing { + globalAlpha: number; + globalCompositeOperation: string; +} + +interface CanvasDrawImage { + drawImage(image: CanvasImageSource, dx: number, dy: number): void; + drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void; + drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; +} + +interface CanvasDrawPath { + beginPath(): void; + clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; + fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(x: number, y: number): boolean; + isPointInStroke(path: Path2D, x: number, y: number): boolean; + stroke(): void; + stroke(path: Path2D): void; +} + +interface CanvasFillStrokeStyles { + fillStyle: string | CanvasGradient | CanvasPattern; + strokeStyle: string | CanvasGradient | CanvasPattern; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: CanvasImageSource, repetition: string): CanvasPattern | null; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; +} + +interface CanvasFilters { + filter: string; } interface CanvasGradient { + /** + * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset + * at one end of the gradient, 1.0 is the offset at the other end. + * Throws an "IndexSizeError" DOMException if the offset + * is out of range. Throws a "SyntaxError" DOMException if + * the color cannot be parsed. + */ addColorStop(offset: number, color: string): void; } @@ -3193,10 +2922,22 @@ declare var CanvasGradient: { new(): CanvasGradient; }; -interface CanvasPathMethods { +interface CanvasImageData { + createImageData(sw: number, sh: number): ImageData; + createImageData(imagedata: ImageData): ImageData; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + putImageData(imagedata: ImageData, dx: number, dy: number): void; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void; +} + +interface CanvasImageSmoothing { + imageSmoothingEnabled: boolean; + imageSmoothingQuality: ImageSmoothingQuality; +} + +interface CanvasPath { arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; - arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: number): void; bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; closePath(): void; ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; @@ -3206,8 +2947,22 @@ interface CanvasPathMethods { rect(x: number, y: number, w: number, h: number): void; } +interface CanvasPathDrawingStyles { + lineCap: CanvasLineCap; + lineDashOffset: number; + lineJoin: CanvasLineJoin; + lineWidth: number; + miterLimit: number; + getLineDash(): number[]; + setLineDash(segments: number[]): void; +} + interface CanvasPattern { - setTransform(matrix: SVGMatrix): void; + /** + * Sets the transformation matrix that will be used when rendering the pattern during a fill or + * stroke painting operation. + */ + setTransform(transform?: DOMMatrix2DInit): void; } declare var CanvasPattern: { @@ -3215,70 +2970,73 @@ declare var CanvasPattern: { new(): CanvasPattern; }; -interface CanvasRenderingContext2D extends CanvasPathMethods { +interface CanvasRect { + clearRect(x: number, y: number, w: number, h: number): void; + fillRect(x: number, y: number, w: number, h: number): void; + strokeRect(x: number, y: number, w: number, h: number): void; +} + +interface CanvasRenderingContext2D extends CanvasState, CanvasTransform, CanvasCompositing, CanvasImageSmoothing, CanvasFillStrokeStyles, CanvasShadowStyles, CanvasFilters, CanvasRect, CanvasDrawPath, CanvasUserInterface, CanvasText, CanvasDrawImage, CanvasImageData, CanvasPathDrawingStyles, CanvasTextDrawingStyles, CanvasPath { readonly canvas: HTMLCanvasElement; - fillStyle: string | CanvasGradient | CanvasPattern; - font: string; - globalAlpha: number; - globalCompositeOperation: string; - imageSmoothingEnabled: boolean; - lineCap: string; - lineDashOffset: number; - lineJoin: string; - lineWidth: number; - miterLimit: number; - mozImageSmoothingEnabled: boolean; - msFillRule: CanvasFillRule; - oImageSmoothingEnabled: boolean; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +}; + +interface CanvasShadowStyles { shadowBlur: number; shadowColor: string; shadowOffsetX: number; shadowOffsetY: number; - strokeStyle: string | CanvasGradient | CanvasPattern; - textAlign: string; - textBaseline: string; - webkitImageSmoothingEnabled: boolean; - beginPath(): void; - clearRect(x: number, y: number, w: number, h: number): void; - clip(fillRule?: CanvasFillRule): void; - clip(path: Path2D, fillRule?: CanvasFillRule): void; - createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; - createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; - createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; - createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; - drawFocusIfNeeded(element: Element): void; - drawFocusIfNeeded(path: Path2D, element: Element): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void; - drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void; - fill(fillRule?: CanvasFillRule): void; - fill(path: Path2D, fillRule?: CanvasFillRule): void; - fillRect(x: number, y: number, w: number, h: number): void; +} + +interface CanvasState { + restore(): void; + save(): void; +} + +interface CanvasText { fillText(text: string, x: number, y: number, maxWidth?: number): void; - getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; - getLineDash(): number[]; - isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; - isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; - isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean; - isPointInStroke(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; measureText(text: string): TextMetrics; - putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; - restore(): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; +} + +interface CanvasTextDrawingStyles { + direction: CanvasDirection; + font: string; + textAlign: CanvasTextAlign; + textBaseline: CanvasTextBaseline; +} + +interface CanvasTransform { + getTransform(): DOMMatrix; + resetTransform(): void; rotate(angle: number): void; - save(): void; scale(x: number, y: number): void; - setLineDash(segments: number[]): void; - setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; - stroke(path?: Path2D): void; - strokeRect(x: number, y: number, w: number, h: number): void; - strokeText(text: string, x: number, y: number, maxWidth?: number): void; - transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void; + setTransform(transform?: DOMMatrix2DInit): void; + transform(a: number, b: number, c: number, d: number, e: number, f: number): void; translate(x: number, y: number): void; } -declare var CanvasRenderingContext2D: { - prototype: CanvasRenderingContext2D; - new(): CanvasRenderingContext2D; +interface CanvasUserInterface { + drawFocusIfNeeded(element: Element): void; + drawFocusIfNeeded(path: Path2D, element: Element): void; + scrollPathIntoView(): void; + scrollPathIntoView(path: Path2D): void; +} + +interface CaretPosition { + readonly offset: number; + readonly offsetNode: Node; + getClientRect(): DOMRect | null; +} + +declare var CaretPosition: { + prototype: CaretPosition; + new(): CaretPosition; }; interface ChannelMergerNode extends AudioNode { @@ -3297,13 +3055,13 @@ declare var ChannelSplitterNode: { new(context: BaseAudioContext, options?: ChannelSplitterOptions): ChannelSplitterNode; }; -interface CharacterData extends Node, ChildNode { +interface CharacterData extends Node, NonDocumentTypeChildNode, ChildNode { data: string; readonly length: number; - appendData(arg: string): void; + appendData(data: string): void; deleteData(offset: number, count: number): void; - insertData(offset: number, arg: string): void; - replaceData(offset: number, count: number, arg: string): void; + insertData(offset: number, data: string): void; + replaceData(offset: number, count: number, data: string): void; substringData(offset: number, count: number): string; } @@ -3312,8 +3070,29 @@ declare var CharacterData: { new(): CharacterData; }; -interface ChildNode { +interface ChildNode extends Node { + /** + * Inserts nodes just after node, while replacing strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + after(...nodes: (Node | string)[]): void; + /** + * Inserts nodes just before node, while replacing strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + before(...nodes: (Node | string)[]): void; + /** + * Removes node. + */ remove(): void; + /** + * Replaces node with nodes, while replacing strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + replaceWith(...nodes: (Node | string)[]): void; } interface ClientRect { @@ -3369,7 +3148,6 @@ declare var CloseEvent: { }; interface Comment extends CharacterData { - text: string; } declare var Comment: { @@ -3413,10 +3191,8 @@ interface Console { info(message?: any, ...optionalParams: any[]): void; log(message?: any, ...optionalParams: any[]): void; markTimeline(label?: string): void; - msIsIndependentlyComposed(element: Element): boolean; profile(reportName?: string): void; - profileEnd(): void; - select(element: Element): void; + profileEnd(reportName?: string): void; table(...tabularData: any[]): void; time(label?: string): void; timeEnd(label?: string): void; @@ -3488,8 +3264,8 @@ declare var Crypto: { interface CryptoKey { readonly algorithm: KeyAlgorithm; readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; + readonly type: KeyType; + readonly usages: KeyUsage[]; } declare var CryptoKey: { @@ -3510,10 +3286,20 @@ declare var CryptoKeyPair: { interface CustomElementRegistry { define(name: string, constructor: Function, options?: ElementDefinitionOptions): void; get(name: string): any; - whenDefined(name: string): PromiseLike; + upgrade(root: Node): void; + whenDefined(name: string): Promise; } +declare var CustomElementRegistry: { + prototype: CustomElementRegistry; + new(): CustomElementRegistry; +}; + interface CustomEvent extends Event { + /** + * Returns any custom data event was created with. + * Typically used for synthetic events. + */ readonly detail: T; initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; } @@ -3598,7 +3384,8 @@ interface DOMImplementation { createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document; createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; createHTMLDocument(title?: string): Document; - hasFeature(feature: string | null, version: string | null): boolean; + /** @deprecated */ + hasFeature(...args: any[]): true; } declare var DOMImplementation: { @@ -3610,10 +3397,6 @@ interface DOML2DeprecatedColorProperty { color: string; } -interface DOML2DeprecatedSizeProperty { - size: number; -} - interface DOMMatrix extends DOMMatrixReadOnly { a: number; b: number; @@ -3717,7 +3500,7 @@ declare var DOMMatrixReadOnly: { }; interface DOMParser { - parseFromString(source: string, mimeType: string): Document; + parseFromString(str: string, type: SupportedType): Document; } declare var DOMParser: { @@ -3858,14 +3641,56 @@ declare var DOMStringMap: { }; interface DOMTokenList { + /** + * Returns the number of tokens. + */ readonly length: number; + /** + * Returns the associated set as string. + * Can be set, to change the associated attribute. + */ + value: string; + /** + * Adds all arguments passed, except those already present. + * Throws a "SyntaxError" DOMException if one of the arguments is the empty + * string. + * Throws an "InvalidCharacterError" DOMException if one of the arguments + * contains any ASCII whitespace. + */ add(...tokens: string[]): void; + /** + * Returns true if token is present, and false otherwise. + */ contains(token: string): boolean; + /** + * tokenlist[index] + */ item(index: number): string | null; + /** + * Removes arguments passed, if they are present. + * Throws a "SyntaxError" DOMException if one of the arguments is the empty + * string. + * Throws an "InvalidCharacterError" DOMException if one of the arguments + * contains any ASCII whitespace. + */ remove(...tokens: string[]): void; + /** + * Replaces token with newToken. + * Returns true if token was replaced with newToken, and false otherwise. + * Throws a "SyntaxError" DOMException if one of the arguments is the empty + * string. + * Throws an "InvalidCharacterError" DOMException if one of the arguments + * contains any ASCII whitespace. + */ replace(oldToken: string, newToken: string): void; - toString(): string; + /** + * Returns true if token is in the associated attribute's supported tokens. Returns + * false otherwise. + * Throws a TypeError if the associated attribute has no supported tokens defined. + */ + supports(token: string): boolean; toggle(token: string, force?: boolean): boolean; + forEach(callbackfn: (value: string, key: number, parent: DOMTokenList) => void, thisArg?: any): void; [index: number]: string; } @@ -3890,12 +3715,35 @@ declare var DataCue: { interface DataTransfer { dropEffect: string; effectAllowed: string; + /** + * Returns a FileList of the files being dragged, if any. + */ readonly files: FileList; + /** + * Returns a DataTransferItemList object, with the drag data. + */ readonly items: DataTransferItemList; - readonly types: string[]; - clearData(format?: string): boolean; + /** + * Returns a frozen array listing the formats that were set in the dragstart event. In addition, if any files are being + * dragged, then one of the types will be the string "Files". + */ + readonly types: ReadonlyArray; + /** + * Removes the data of the specified formats. Removes all data if the argument is omitted. + */ + clearData(format?: string): void; + /** + * Returns the specified data. If there is no such data, returns the empty string. + */ getData(format: string): string; - setData(format: string, data: string): boolean; + /** + * Adds the specified data. + */ + setData(format: string, data: string): void; + /** + * Uses the given element to update the drag feedback, replacing any previously specified + * feedback. + */ setDragImage(image: Element, x: number, y: number): void; } @@ -3905,10 +3753,24 @@ declare var DataTransfer: { }; interface DataTransferItem { + /** + * Returns the drag data item kind, one of: "string", + * "file". + */ readonly kind: string; + /** + * Returns the drag data item type string. + */ readonly type: string; + /** + * Returns a File object, if the drag data item kind is File. + */ getAsFile(): File | null; - getAsString(_callback: FunctionStringCallback | null): void; + /** + * Invokes the callback with the string data as the argument, if the drag data item + * kind is Plain Unicode string. + */ + getAsString(callback: FunctionStringCallback | null): void; webkitGetAsEntry(): any; } @@ -3918,11 +3780,25 @@ declare var DataTransferItem: { }; interface DataTransferItemList { + /** + * Returns the number of items in the drag data store. + */ readonly length: number; - add(data: File): DataTransferItem | null; + /** + * Adds a new entry for the given data to the drag data store. If the data is plain + * text then a type string has to be provided + * also. + */ add(data: string, type: string): DataTransferItem | null; + add(data: File): DataTransferItem | null; + /** + * Removes all the entries in the drag data store. + */ clear(): void; item(index: number): DataTransferItem; + /** + * Removes the indexth entry in the drag data store. + */ remove(index: number): void; [name: number]: DataTransferItem; } @@ -4030,110 +3906,22 @@ interface DhKeyGenParams extends Algorithm { prime: Uint8Array; } -interface DocumentEventMap extends GlobalEventHandlersEventMap { - "abort": UIEvent; - "activate": Event; - "beforeactivate": Event; - "beforedeactivate": Event; - "blur": FocusEvent; - "canplay": Event; - "canplaythrough": Event; - "change": Event; - "click": MouseEvent; - "contextmenu": PointerEvent; - "dblclick": MouseEvent; - "deactivate": Event; - "drag": DragEvent; - "dragend": DragEvent; - "dragenter": DragEvent; - "dragleave": DragEvent; - "dragover": DragEvent; - "dragstart": DragEvent; - "drop": DragEvent; - "durationchange": Event; - "emptied": Event; - "ended": Event; - "error": ErrorEvent; - "focus": FocusEvent; +interface DocumentEventMap extends GlobalEventHandlersEventMap, DocumentAndElementEventHandlersEventMap { "fullscreenchange": Event; "fullscreenerror": Event; - "input": Event; - "invalid": Event; - "keydown": KeyboardEvent; - "keypress": KeyboardEvent; - "keyup": KeyboardEvent; - "load": Event; - "loadeddata": Event; - "loadedmetadata": Event; - "loadstart": Event; - "mousedown": MouseEvent; - "mousemove": MouseEvent; - "mouseout": MouseEvent; - "mouseover": MouseEvent; - "mouseup": MouseEvent; - "mousewheel": WheelEvent; - "MSContentZoom": Event; - "MSGestureChange": Event; - "MSGestureDoubleTap": Event; - "MSGestureEnd": Event; - "MSGestureHold": Event; - "MSGestureStart": Event; - "MSGestureTap": Event; - "MSInertiaStart": Event; - "MSManipulationStateChanged": Event; - "MSPointerCancel": Event; - "MSPointerDown": Event; - "MSPointerEnter": Event; - "MSPointerLeave": Event; - "MSPointerMove": Event; - "MSPointerOut": Event; - "MSPointerOver": Event; - "MSPointerUp": Event; - "mssitemodejumplistitemremoved": Event; - "msthumbnailclick": Event; - "pause": Event; - "play": Event; - "playing": Event; - "pointerlockchange": Event; - "pointerlockerror": Event; - "progress": ProgressEvent; - "ratechange": Event; - "readystatechange": Event; - "reset": Event; - "scroll": UIEvent; - "seeked": Event; - "seeking": Event; - "select": UIEvent; - "selectionchange": Event; - "selectstart": Event; - "stalled": Event; - "stop": Event; - "submit": Event; - "suspend": Event; - "timeupdate": Event; - "touchcancel": TouchEvent; - "touchend": TouchEvent; - "touchmove": TouchEvent; - "touchstart": TouchEvent; - "volumechange": Event; - "waiting": Event; - "webkitfullscreenchange": Event; - "webkitfullscreenerror": Event; + "readystatechange": ProgressEvent; + "visibilitychange": Event; } -interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent { +interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, ParentNode, GlobalEventHandlers, DocumentAndElementEventHandlers { /** * Sets or gets the URL for the current document. */ readonly URL: string; - /** - * Gets the URL for the document, stripped of any character encoding. - */ - readonly URLUnencoded: string; /** * Gets the object that has the focus when the parent document has focus. */ - readonly activeElement: Element; + readonly activeElement: Element | null; /** * Sets or gets the color of all active links in the document. */ @@ -4163,18 +3951,44 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * Specifies the beginning and end of the document body. */ body: HTMLElement; + /** + * Returns document's encoding. + */ readonly characterSet: string; /** * Gets or sets the character set used to encode the object. */ - charset: string; + readonly charset: string; /** * Gets a value that indicates whether standards-compliant mode is switched on for the object. */ readonly compatMode: string; + /** + * Returns document's content type. + */ + readonly contentType: string; + /** + * Returns the HTTP cookies that apply to the Document. If there are no cookies or + * cookies can't be applied to this resource, the empty string will be returned. + * Can be set, to add a new cookie to the element's set of HTTP cookies. + * If the contents are sandboxed into a + * unique origin (e.g. in an iframe with the sandbox attribute), a + * "SecurityError" DOMException will be thrown on getting + * and setting. + */ cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement | null; - readonly defaultView: Window; + /** + * Returns the script element, or the SVG script element, + * that is currently executing, as long as the element represents a classic script. + * In the case of reentrant script execution, returns the one that most recently started executing + * amongst those that have not yet finished executing. + * Returns null if the Document is not currently executing a script + * or SVG script element (e.g., because the running script is an event + * handler, or a timeout), or if the currently executing script or SVG + * script element represents a module script. + */ + readonly currentScript: HTMLOrSVGScriptElement | null; + readonly defaultView: WindowProxy | null; /** * Sets or gets a value that indicates whether the document can be edited. */ @@ -4186,11 +4000,15 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent /** * Gets an object representing the document type declaration associated with the current document. */ - readonly doctype: DocumentType; + readonly doctype: DocumentType | null; /** * Gets a reference to the root node of the document. */ - readonly documentElement: HTMLElement; + readonly documentElement: HTMLElement | null; + /** + * Returns document's URL. + */ + readonly documentURI: string; /** * Sets or gets the security domain of the document. */ @@ -4208,9 +4026,17 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * Retrieves a collection, in source order, of all form objects in the document. */ readonly forms: HTMLCollectionOf; - readonly fullscreenElement: Element | null; + /** @deprecated */ + readonly fullscreen: boolean; + /** + * Returns true if document has the ability to display elements fullscreen + * and fullscreen is supported, or false otherwise. + */ readonly fullscreenEnabled: boolean; - readonly head: HTMLHeadElement; + /** + * Returns the head element. + */ + readonly head: HTMLHeadElement | null; readonly hidden: boolean; /** * Retrieves a collection, in source order, of img objects in the document. @@ -4223,7 +4049,7 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent /** * Returns the character encoding used to create the webpage that is loaded into the document object. */ - readonly inputEncoding: string | null; + readonly inputEncoding: string; /** * Gets the date that the page was last modified, if the page supplies one. */ @@ -4240,390 +4066,104 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent /** * Contains information about the current URL. */ - location: Location; - msCSSOMElementFloatMetrics: boolean; - msCapsLockWarningOff: boolean; - /** - * Fires when the user aborts the download. - * @param ev The event. - */ - onabort: ((this: Document, ev: UIEvent) => any) | null; - /** - * Fires when the object is set as the active element. - * @param ev The event. - */ - onactivate: ((this: Document, ev: Event) => any) | null; - /** - * Fires immediately before the object is set as the active element. - * @param ev The event. - */ - onbeforeactivate: ((this: Document, ev: Event) => any) | null; - /** - * Fires immediately before the activeElement is changed from the current object to another object in the parent document. - * @param ev The event. - */ - onbeforedeactivate: ((this: Document, ev: Event) => any) | null; - /** - * Fires when the object loses the input focus. - * @param ev The focus event. - */ - onblur: ((this: Document, ev: FocusEvent) => any) | null; - /** - * Occurs when playback is possible, but would require further buffering. - * @param ev The event. - */ - oncanplay: ((this: Document, ev: Event) => any) | null; - oncanplaythrough: ((this: Document, ev: Event) => any) | null; - /** - * Fires when the contents of the object or selection have changed. - * @param ev The event. - */ - onchange: ((this: Document, ev: Event) => any) | null; - /** - * Fires when the user clicks the left mouse button on the object - * @param ev The mouse event. - */ - onclick: ((this: Document, ev: MouseEvent) => any) | null; - /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. - * @param ev The mouse event. - */ - oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null; - /** - * Fires when the user double-clicks the object. - * @param ev The mouse event. - */ - ondblclick: ((this: Document, ev: MouseEvent) => any) | null; + location: Location | null; + onfullscreenchange: ((this: Document, ev: Event) => any) | null; + onfullscreenerror: ((this: Document, ev: Event) => any) | null; /** - * Fires when the activeElement is changed from the current object to another object in the parent document. - * @param ev The UI Event + * Fires when the state of the object has changed. + * @param ev The event */ - ondeactivate: ((this: Document, ev: Event) => any) | null; + onreadystatechange: ((this: Document, ev: ProgressEvent) => any) | null; + onvisibilitychange: ((this: Document, ev: Event) => any) | null; /** - * Fires on the source object continuously during a drag operation. - * @param ev The event. + * Returns document's origin. */ - ondrag: ((this: Document, ev: DragEvent) => any) | null; + readonly origin: string; /** - * Fires on the source object when the user releases the mouse at the close of a drag operation. - * @param ev The event. + * Return an HTMLCollection of the embed elements in the Document. */ - ondragend: ((this: Document, ev: DragEvent) => any) | null; + readonly plugins: HTMLCollectionOf; /** - * Fires on the target element when the user drags the object to a valid drop target. - * @param ev The drag event. + * Retrieves a value that indicates the current state of the object. */ - ondragenter: ((this: Document, ev: DragEvent) => any) | null; + readonly readyState: DocumentReadyState; /** - * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. - * @param ev The drag event. + * Gets the URL of the location that referred the user to the current page. */ - ondragleave: ((this: Document, ev: DragEvent) => any) | null; + readonly referrer: string; /** - * Fires on the target element continuously while the user drags the object over a valid drop target. - * @param ev The event. + * Retrieves a collection of all script objects in the document. */ - ondragover: ((this: Document, ev: DragEvent) => any) | null; + readonly scripts: HTMLCollectionOf; + readonly scrollingElement: Element | null; + readonly timeline: DocumentTimeline; /** - * Fires on the source object when the user starts to drag a text selection or selected object. - * @param ev The event. + * Contains the title of the document. */ - ondragstart: ((this: Document, ev: DragEvent) => any) | null; - ondrop: ((this: Document, ev: DragEvent) => any) | null; + title: string; + readonly visibilityState: VisibilityState; /** - * Occurs when the duration attribute is updated. - * @param ev The event. + * Sets or gets the color of the links that the user has visited. */ - ondurationchange: ((this: Document, ev: Event) => any) | null; + /** @deprecated */ + vlinkColor: string; /** - * Occurs when the media element is reset to its initial state. - * @param ev The event. + * Moves node from another document and returns it. + * If node is a document, throws a "NotSupportedError" DOMException or, if node is a shadow root, throws a + * "HierarchyRequestError" DOMException. */ - onemptied: ((this: Document, ev: Event) => any) | null; + adoptNode(source: T): T; + /** @deprecated */ + captureEvents(): void; + caretPositionFromPoint(x: number, y: number): CaretPosition | null; + caretRangeFromPoint(x: number, y: number): Range; + /** @deprecated */ + clear(): void; /** - * Occurs when the end of playback is reached. - * @param ev The event + * Closes an output stream and forces the sent data to display. */ - onended: ((this: Document, ev: Event) => any) | null; + close(): void; /** - * Fires when an error occurs during object loading. - * @param ev The event. + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. */ - onerror: ((this: Document, ev: ErrorEvent) => any) | null; + createAttribute(localName: string): Attr; + createAttributeNS(namespace: string | null, qualifiedName: string): Attr; /** - * Fires when the object receives focus. - * @param ev The event. + * Returns a CDATASection node whose data is data. */ - onfocus: ((this: Document, ev: FocusEvent) => any) | null; - onfullscreenchange: ((this: Document, ev: Event) => any) | null; - onfullscreenerror: ((this: Document, ev: Event) => any) | null; - oninput: ((this: Document, ev: Event) => any) | null; - oninvalid: ((this: Document, ev: Event) => any) | null; + createCDATASection(data: string): CDATASection; /** - * Fires when the user presses a key. - * @param ev The keyboard event + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. */ - onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null; + createComment(data: string): Comment; /** - * Fires when the user presses an alphanumeric key. - * @param ev The event. + * Creates a new document. */ - onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null; + createDocumentFragment(): DocumentFragment; /** - * Fires when the user releases a key. - * @param ev The keyboard event + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. */ - onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null; + createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; + /** @deprecated */ + createElement(tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; + createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; /** - * Fires immediately after the browser loads the object. - * @param ev The event. + * Returns an element with namespace namespace. Its namespace prefix will be everything before ":" (U+003E) in qualifiedName or null. Its local name will be everything after + * ":" (U+003E) in qualifiedName or qualifiedName. + * If localName does not match the Name production an + * "InvalidCharacterError" DOMException will be thrown. + * If one of the following conditions is true a "NamespaceError" DOMException will be thrown: + * localName does not match the QName production. + * Namespace prefix is not null and namespace is the empty string. + * Namespace prefix is "xml" and namespace is not the XML namespace. + * qualifiedName or namespace prefix is "xmlns" and namespace is not the XMLNS namespace. + * namespace is the XMLNS namespace and + * neither qualifiedName nor namespace prefix is "xmlns". + * When supplied, options's is can be used to create a customized built-in element. */ - onload: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when media data is loaded at the current playback position. - * @param ev The event. - */ - onloadeddata: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when the duration and dimensions of the media have been determined. - * @param ev The event. - */ - onloadedmetadata: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when Internet Explorer begins looking for media data. - * @param ev The event. - */ - onloadstart: ((this: Document, ev: Event) => any) | null; - /** - * Fires when the user clicks the object with either mouse button. - * @param ev The mouse event. - */ - onmousedown: ((this: Document, ev: MouseEvent) => any) | null; - /** - * Fires when the user moves the mouse over the object. - * @param ev The mouse event. - */ - onmousemove: ((this: Document, ev: MouseEvent) => any) | null; - /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. - * @param ev The mouse event. - */ - onmouseout: ((this: Document, ev: MouseEvent) => any) | null; - /** - * Fires when the user moves the mouse pointer into the object. - * @param ev The mouse event. - */ - onmouseover: ((this: Document, ev: MouseEvent) => any) | null; - /** - * Fires when the user releases a mouse button while the mouse is over the object. - * @param ev The mouse event. - */ - onmouseup: ((this: Document, ev: MouseEvent) => any) | null; - /** - * Fires when the wheel button is rotated. - * @param ev The mouse event - */ - onmousewheel: ((this: Document, ev: WheelEvent) => any) | null; - onmscontentzoom: ((this: Document, ev: Event) => any) | null; - onmsgesturechange: ((this: Document, ev: Event) => any) | null; - onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null; - onmsgestureend: ((this: Document, ev: Event) => any) | null; - onmsgesturehold: ((this: Document, ev: Event) => any) | null; - onmsgesturestart: ((this: Document, ev: Event) => any) | null; - onmsgesturetap: ((this: Document, ev: Event) => any) | null; - onmsinertiastart: ((this: Document, ev: Event) => any) | null; - onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null; - onmspointercancel: ((this: Document, ev: Event) => any) | null; - onmspointerdown: ((this: Document, ev: Event) => any) | null; - onmspointerenter: ((this: Document, ev: Event) => any) | null; - onmspointerleave: ((this: Document, ev: Event) => any) | null; - onmspointermove: ((this: Document, ev: Event) => any) | null; - onmspointerout: ((this: Document, ev: Event) => any) | null; - onmspointerover: ((this: Document, ev: Event) => any) | null; - onmspointerup: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. - * @param ev The event. - */ - onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. - * @param ev The event. - */ - onmsthumbnailclick: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when playback is paused. - * @param ev The event. - */ - onpause: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when the play method is requested. - * @param ev The event. - */ - onplay: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when the audio or video has started playing. - * @param ev The event. - */ - onplaying: ((this: Document, ev: Event) => any) | null; - onpointerlockchange: ((this: Document, ev: Event) => any) | null; - onpointerlockerror: ((this: Document, ev: Event) => any) | null; - /** - * Occurs to indicate progress while downloading media data. - * @param ev The event. - */ - onprogress: ((this: Document, ev: ProgressEvent) => any) | null; - /** - * Occurs when the playback rate is increased or decreased. - * @param ev The event. - */ - onratechange: ((this: Document, ev: Event) => any) | null; - /** - * Fires when the state of the object has changed. - * @param ev The event - */ - onreadystatechange: ((this: Document, ev: Event) => any) | null; - /** - * Fires when the user resets a form. - * @param ev The event. - */ - onreset: ((this: Document, ev: Event) => any) | null; - /** - * Fires when the user repositions the scroll box in the scroll bar on the object. - * @param ev The event. - */ - onscroll: ((this: Document, ev: UIEvent) => any) | null; - /** - * Occurs when the seek operation ends. - * @param ev The event. - */ - onseeked: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when the current playback position is moved. - * @param ev The event. - */ - onseeking: ((this: Document, ev: Event) => any) | null; - /** - * Fires when the current selection changes. - * @param ev The event. - */ - onselect: ((this: Document, ev: UIEvent) => any) | null; - /** - * Fires when the selection state of a document changes. - * @param ev The event. - */ - onselectionchange: ((this: Document, ev: Event) => any) | null; - onselectstart: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when the download has stopped. - * @param ev The event. - */ - onstalled: ((this: Document, ev: Event) => any) | null; - /** - * Fires when the user clicks the Stop button or leaves the Web page. - * @param ev The event. - */ - onstop: ((this: Document, ev: Event) => any) | null; - onsubmit: ((this: Document, ev: Event) => any) | null; - /** - * Occurs if the load operation has been intentionally halted. - * @param ev The event. - */ - onsuspend: ((this: Document, ev: Event) => any) | null; - /** - * Occurs to indicate the current playback position. - * @param ev The event. - */ - ontimeupdate: ((this: Document, ev: Event) => any) | null; - onvisibilitychange: (this: Document, ev: Event) => any; - /** - * Occurs when the volume is changed, or playback is muted or unmuted. - * @param ev The event. - */ - onvolumechange: ((this: Document, ev: Event) => any) | null; - /** - * Occurs when playback stops because the next frame of a video resource is not available. - * @param ev The event. - */ - onwaiting: ((this: Document, ev: Event) => any) | null; - onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null; - onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null; - readonly plugins: HTMLCollectionOf; - readonly pointerLockElement: Element; - /** - * Retrieves a value that indicates the current state of the object. - */ - readonly readyState: DocumentReadyState; - /** - * Gets the URL of the location that referred the user to the current page. - */ - readonly referrer: string; - /** - * Gets the root svg element in the document hierarchy. - */ - readonly rootElement: SVGSVGElement; - /** - * Retrieves a collection of all script objects in the document. - */ - readonly scripts: HTMLCollectionOf; - readonly scrollingElement: Element | null; - /** - * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. - */ - readonly styleSheets: StyleSheetList; - readonly timeline: DocumentTimeline; - /** - * Contains the title of the document. - */ - title: string; - readonly visibilityState: VisibilityState; - /** - * Sets or gets the color of the links that the user has visited. - */ - /** @deprecated */ - vlinkColor: string; - readonly webkitCurrentFullScreenElement: Element | null; - readonly webkitFullscreenElement: Element | null; - readonly webkitFullscreenEnabled: boolean; - readonly webkitIsFullScreen: boolean; - readonly xmlEncoding: string | null; - xmlStandalone: boolean; - /** - * Gets or sets the version attribute specified in the declaration of an XML document. - */ - xmlVersion: string | null; - adoptNode(source: T): T; - /** @deprecated */ - captureEvents(): void; - caretRangeFromPoint(x: number, y: number): Range; - /** @deprecated */ - clear(): void; - /** - * Closes an output stream and forces the sent data to display. - */ - close(): void; - /** - * Creates an attribute object with a specified name. - * @param name String that sets the attribute object's name. - */ - createAttribute(name: string): Attr; - createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr; - createCDATASection(data: string): CDATASection; - /** - * Creates a comment object with the specified data. - * @param data Sets the comment object's data. - */ - createComment(data: string): Comment; - /** - * Creates a new document. - */ - createDocumentFragment(): DocumentFragment; - /** - * Creates an instance of the element for the specified tag. - * @param tagName The name of an element. - */ - createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; - createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement; createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement; @@ -4687,9 +4227,86 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement; createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement; createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement; - createElementNS(namespaceURI: string | null, qualifiedName: string): Element; - createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; - createNSResolver(nodeResolver: Node): XPathNSResolver; + createElementNS(namespaceURI: string | null, qualifiedName: string, options?: ElementCreationOptions): Element; + createElementNS(namespace: string | null, qualifiedName: string, options?: string | ElementCreationOptions): Element; + createEvent(eventInterface: "AnimationEvent"): AnimationEvent; + createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; + createEvent(eventInterface: "AudioProcessingEvent"): AudioProcessingEvent; + createEvent(eventInterface: "BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface: "ClipboardEvent"): ClipboardEvent; + createEvent(eventInterface: "CloseEvent"): CloseEvent; + createEvent(eventInterface: "CompositionEvent"): CompositionEvent; + createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; + createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface: "DragEvent"): DragEvent; + createEvent(eventInterface: "ErrorEvent"): ErrorEvent; + createEvent(eventInterface: "Event"): Event; + createEvent(eventInterface: "Events"): Event; + createEvent(eventInterface: "FocusEvent"): FocusEvent; + createEvent(eventInterface: "FocusNavigationEvent"): FocusNavigationEvent; + createEvent(eventInterface: "GamepadEvent"): GamepadEvent; + createEvent(eventInterface: "HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; + createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; + createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; + createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; + createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; + createEvent(eventInterface: "MessageEvent"): MessageEvent; + createEvent(eventInterface: "MouseEvent"): MouseEvent; + createEvent(eventInterface: "MouseEvents"): MouseEvent; + createEvent(eventInterface: "MutationEvent"): MutationEvent; + createEvent(eventInterface: "MutationEvents"): MutationEvent; + createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface: "OverflowEvent"): OverflowEvent; + createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; + createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface: "PointerEvent"): PointerEvent; + createEvent(eventInterface: "PopStateEvent"): PopStateEvent; + createEvent(eventInterface: "ProgressEvent"): ProgressEvent; + createEvent(eventInterface: "PromiseRejectionEvent"): PromiseRejectionEvent; + createEvent(eventInterface: "RTCDTMFToneChangeEvent"): RTCDTMFToneChangeEvent; + createEvent(eventInterface: "RTCDataChannelEvent"): RTCDataChannelEvent; + createEvent(eventInterface: "RTCDtlsTransportStateChangedEvent"): RTCDtlsTransportStateChangedEvent; + createEvent(eventInterface: "RTCErrorEvent"): RTCErrorEvent; + createEvent(eventInterface: "RTCIceCandidatePairChangedEvent"): RTCIceCandidatePairChangedEvent; + createEvent(eventInterface: "RTCIceGathererEvent"): RTCIceGathererEvent; + createEvent(eventInterface: "RTCIceTransportStateChangedEvent"): RTCIceTransportStateChangedEvent; + createEvent(eventInterface: "RTCPeerConnectionIceErrorEvent"): RTCPeerConnectionIceErrorEvent; + createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; + createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; + createEvent(eventInterface: "RTCStatsEvent"): RTCStatsEvent; + createEvent(eventInterface: "RTCTrackEvent"): RTCTrackEvent; + createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; + createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechRecognitionError"): SpeechRecognitionError; + createEvent(eventInterface: "SpeechRecognitionEvent"): SpeechRecognitionEvent; + createEvent(eventInterface: "SpeechSynthesisErrorEvent"): SpeechSynthesisErrorEvent; + createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; + createEvent(eventInterface: "StorageEvent"): StorageEvent; + createEvent(eventInterface: "TextEvent"): TextEvent; + createEvent(eventInterface: "TouchEvent"): TouchEvent; + createEvent(eventInterface: "TrackEvent"): TrackEvent; + createEvent(eventInterface: "TransitionEvent"): TransitionEvent; + createEvent(eventInterface: "UIEvent"): UIEvent; + createEvent(eventInterface: "UIEvents"): UIEvent; + createEvent(eventInterface: "VRDisplayEvent"): VRDisplayEvent; + createEvent(eventInterface: "VRDisplayEvent "): VRDisplayEvent ; + createEvent(eventInterface: "WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface: "WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; /** * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. * @param root The root element or node to start traversing on. @@ -4697,7 +4314,14 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. */ - createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter | null): NodeIterator; + /** + * Returns a ProcessingInstruction node whose target is target and data is data. + * If target does not match the Name production an + * "InvalidCharacterError" DOMException will be thrown. + * If data contains "?>" an + * "InvalidCharacterError" DOMException will be thrown. + */ createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. @@ -4708,7 +4332,7 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * @param data String that specifies the nodeValue property of the text node. */ createTextNode(data: string): Text; - createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; + createTouch(view: WindowProxy, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; createTouchList(...touches: Touch[]): TouchList; /** * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. @@ -4717,13 +4341,13 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * @param filter A custom NodeFilter function to use. * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. */ - createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter | null, entityReferenceExpansion?: boolean): TreeWalker; /** * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset * @param y The y-offset */ - elementFromPoint(x: number, y: number): Element; + elementFromPoint(x: number, y: number): Element | null; elementsFromPoint(x: number, y: number): Element[]; evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; /** @@ -4732,25 +4356,21 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * @param showUI Display the user interface, defaults to false. * @param value Value to assign. */ - execCommand(commandId: string, showUI?: boolean, value?: any): boolean; - /** - * Displays help information for the given command identifier. - * @param commandId Displays help information for the given command identifier. - */ - execCommandShowHelp(commandId: string): boolean; - exitFullscreen(): void; - exitPointerLock(): void; + execCommand(commandId: string, showUI?: boolean, value?: string): boolean; /** - * Causes the element to receive the focus and executes the code specified by the onfocus event. + * Stops document's fullscreen element from being displayed fullscreen and + * resolves promise when done. */ - /** @deprecated */ - focus(): void; + exitFullscreen(): Promise; getAnimations(): Animation[]; /** * Returns a reference to the first object with the specified value of the ID or NAME attribute. * @param elementId String that specifies the ID value. Case-insensitive. */ getElementById(elementId: string): HTMLElement | null; + /** + * collection = element . getElementsByClassName(classNames) + */ getElementsByClassName(classNames: string): HTMLCollectionOf; /** * Gets a collection of objects based on the value of the NAME or ID attribute. @@ -4761,23 +4381,24 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * Retrieves a collection of objects based on the specified element name. * @param name Specifies the name of an element. */ - getElementsByTagName(tagname: K): NodeListOf; - getElementsByTagName(tagname: K): NodeListOf; - getElementsByTagName(tagname: string): NodeListOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: string): HTMLCollectionOf; + /** + * If namespace and localName are + * "*" returns a HTMLCollection of all descendant elements. + * If only namespace is "*" returns a HTMLCollection of all descendant elements whose local name is localName. + * If only localName is "*" returns a HTMLCollection of all descendant elements whose namespace is namespace. + * Otherwise, returns a HTMLCollection of all descendant elements whose namespace is namespace and local name is localName. + */ getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; - /** - * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. - */ - getSelection(): Selection; /** * Gets a value indicating whether the object currently has focus. */ hasFocus(): boolean; importNode(importedNode: T, deep: boolean): T; - msElementsFromPoint(x: number, y: number): NodeListOf; - msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf; /** * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. * @param url Specifies a MIME type for the document. @@ -4806,11 +4427,6 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent * @param commandId Specifies a command identifier. */ queryCommandSupported(commandId: string): boolean; - /** - * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. - */ - queryCommandText(commandId: string): string; /** * Returns the current value of the document, range, or current selection for the given command. * @param commandId String that specifies a command identifier. @@ -4818,19 +4434,19 @@ interface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent queryCommandValue(commandId: string): string; /** @deprecated */ releaseEvents(): void; - updateSettings(): void; - webkitCancelFullScreen(): void; - webkitExitFullscreen(): void; /** * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. */ - write(...content: string[]): void; + write(...text: string[]): void; /** * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. * @param content The text and HTML tags to write. */ - writeln(...content: string[]): void; + writeln(...text: string[]): void; + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -4842,6 +4458,22 @@ declare var Document: { new(): Document; }; +interface DocumentAndElementEventHandlersEventMap { + "copy": ClipboardEvent; + "cut": ClipboardEvent; + "paste": ClipboardEvent; +} + +interface DocumentAndElementEventHandlers { + oncopy: ((this: DocumentAndElementEventHandlers, ev: ClipboardEvent) => any) | null; + oncut: ((this: DocumentAndElementEventHandlers, ev: ClipboardEvent) => any) | null; + onpaste: ((this: DocumentAndElementEventHandlers, ev: ClipboardEvent) => any) | null; + addEventListener(type: K, listener: (this: DocumentAndElementEventHandlers, ev: DocumentAndElementEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: DocumentAndElementEventHandlers, ev: DocumentAndElementEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + interface DocumentEvent { createEvent(eventInterface: "AnimationEvent"): AnimationEvent; createEvent(eventInterface: "AnimationPlaybackEvent"): AnimationPlaybackEvent; @@ -4865,12 +4497,13 @@ interface DocumentEvent { createEvent(eventInterface: "IDBVersionChangeEvent"): IDBVersionChangeEvent; createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface: "MSDCCEvent"): MSDCCEvent; - createEvent(eventInterface: "MSDSHEvent"): MSDSHEvent; + createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; + createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; createEvent(eventInterface: "MediaStreamErrorEvent"): MediaStreamErrorEvent; createEvent(eventInterface: "MediaStreamEvent"): MediaStreamEvent; createEvent(eventInterface: "MediaStreamTrackEvent"): MediaStreamTrackEvent; @@ -4904,6 +4537,9 @@ interface DocumentEvent { createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; createEvent(eventInterface: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; + createEvent(eventInterface: "SpeechRecognitionError"): SpeechRecognitionError; + createEvent(eventInterface: "SpeechRecognitionEvent"): SpeechRecognitionEvent; + createEvent(eventInterface: "SpeechSynthesisErrorEvent"): SpeechSynthesisErrorEvent; createEvent(eventInterface: "SpeechSynthesisEvent"): SpeechSynthesisEvent; createEvent(eventInterface: "StorageEvent"): StorageEvent; createEvent(eventInterface: "TextEvent"): TextEvent; @@ -4919,7 +4555,7 @@ interface DocumentEvent { createEvent(eventInterface: string): Event; } -interface DocumentFragment extends Node, ParentNode { +interface DocumentFragment extends Node, NonElementParentNode, ParentNode { getElementById(elementId: string): HTMLElement | null; } @@ -4930,6 +4566,9 @@ declare var DocumentFragment: { interface DocumentOrShadowRoot { readonly activeElement: Element | null; + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ readonly styleSheets: StyleSheetList; elementFromPoint(x: number, y: number): Element | null; elementsFromPoint(x: number, y: number): Element[]; @@ -4945,10 +4584,7 @@ declare var DocumentTimeline: { }; interface DocumentType extends Node, ChildNode { - readonly entities: NamedNodeMap; - readonly internalSubset: string | null; readonly name: string; - readonly notations: NamedNodeMap; readonly publicId: string; readonly systemId: string; } @@ -4959,14 +4595,15 @@ declare var DocumentType: { }; interface DragEvent extends MouseEvent { - readonly dataTransfer: DataTransfer; - initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; - msConvertURL(file: File, targetType: string, targetURL?: string): void; + /** + * Returns the DataTransfer object for the event. + */ + readonly dataTransfer: DataTransfer | null; } declare var DragEvent: { prototype: DragEvent; - new(type: "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent; + new(type: string, eventInitDict?: DragEventInit): DragEvent; }; interface DynamicsCompressorNode extends AudioNode { @@ -5007,122 +4644,142 @@ interface EXT_texture_filter_anisotropic { } declare var EXT_texture_filter_anisotropic: { - prototype: EXT_texture_filter_anisotropic; - new(): EXT_texture_filter_anisotropic; - readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; - readonly TEXTURE_MAX_ANISOTROPY_EXT: number; -}; - -interface ElementEventMap extends GlobalEventHandlersEventMap { - "ariarequest": Event; - "command": Event; - "gotpointercapture": PointerEvent; - "lostpointercapture": PointerEvent; - "MSGestureChange": Event; - "MSGestureDoubleTap": Event; - "MSGestureEnd": Event; - "MSGestureHold": Event; - "MSGestureStart": Event; - "MSGestureTap": Event; - "MSGotPointerCapture": Event; - "MSInertiaStart": Event; - "MSLostPointerCapture": Event; - "MSPointerCancel": Event; - "MSPointerDown": Event; - "MSPointerEnter": Event; - "MSPointerLeave": Event; - "MSPointerMove": Event; - "MSPointerOut": Event; - "MSPointerOver": Event; - "MSPointerUp": Event; - "touchcancel": TouchEvent; - "touchend": TouchEvent; - "touchmove": TouchEvent; - "touchstart": TouchEvent; - "webkitfullscreenchange": Event; - "webkitfullscreenerror": Event; + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + readonly TEXTURE_MAX_ANISOTROPY_EXT: number; +}; + +interface ElementEventMap { + "fullscreenchange": Event; + "fullscreenerror": Event; } -interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode, Animatable { +interface Element extends Node, ParentNode, NonDocumentTypeChildNode, ChildNode, Slotable, Animatable { readonly assignedSlot: HTMLSlotElement | null; readonly attributes: NamedNodeMap; + /** + * Allows for manipulation of element's class content attribute as a + * set of whitespace-separated tokens through a DOMTokenList object. + */ readonly classList: DOMTokenList; + /** + * Returns the value of element's class content attribute. Can be set + * to change it. + */ className: string; readonly clientHeight: number; readonly clientLeft: number; readonly clientTop: number; readonly clientWidth: number; + /** + * Returns the value of element's id content attribute. Can be set to + * change it. + */ id: string; innerHTML: string; - msContentZoomFactor: number; - readonly msRegionOverflow: string; - onariarequest: ((this: Element, ev: Event) => any) | null; - oncommand: ((this: Element, ev: Event) => any) | null; - onmsgesturechange: ((this: Element, ev: Event) => any) | null; - onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null; - onmsgestureend: ((this: Element, ev: Event) => any) | null; - onmsgesturehold: ((this: Element, ev: Event) => any) | null; - onmsgesturestart: ((this: Element, ev: Event) => any) | null; - onmsgesturetap: ((this: Element, ev: Event) => any) | null; - onmsgotpointercapture: ((this: Element, ev: Event) => any) | null; - onmsinertiastart: ((this: Element, ev: Event) => any) | null; - onmslostpointercapture: ((this: Element, ev: Event) => any) | null; - onmspointercancel: ((this: Element, ev: Event) => any) | null; - onmspointerdown: ((this: Element, ev: Event) => any) | null; - onmspointerenter: ((this: Element, ev: Event) => any) | null; - onmspointerleave: ((this: Element, ev: Event) => any) | null; - onmspointermove: ((this: Element, ev: Event) => any) | null; - onmspointerout: ((this: Element, ev: Event) => any) | null; - onmspointerover: ((this: Element, ev: Event) => any) | null; - onmspointerup: ((this: Element, ev: Event) => any) | null; - onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null; - onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null; + /** + * Returns the local name. + */ + readonly localName: string; + /** + * Returns the namespace. + */ + readonly namespaceURI: string | null; + onfullscreenchange: ((this: Element, ev: Event) => any) | null; + onfullscreenerror: ((this: Element, ev: Event) => any) | null; outerHTML: string; + /** + * Returns the namespace prefix. + */ readonly prefix: string | null; readonly scrollHeight: number; scrollLeft: number; scrollTop: number; readonly scrollWidth: number; + /** + * Returns element's shadow root, if any, and if shadow root's mode is "open", and null otherwise. + */ readonly shadowRoot: ShadowRoot | null; + /** + * Returns the value of element's slot content attribute. Can be set to + * change it. + */ slot: string; + /** + * Returns the HTML-uppercased qualified name. + */ readonly tagName: string; + /** + * Creates a shadow root for element and returns it. + */ attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot; + /** + * Returns the first (starting at element) inclusive ancestor that matches selectors, and null otherwise. + */ closest(selector: K): HTMLElementTagNameMap[K] | null; closest(selector: K): SVGElementTagNameMap[K] | null; closest(selector: string): Element | null; + /** + * Returns element's first attribute whose qualified name is qualifiedName, and null if there is no such attribute otherwise. + */ getAttribute(qualifiedName: string): string | null; - getAttributeNS(namespaceURI: string, localName: string): string; + /** + * Returns element's attribute whose namespace is namespace and local name is localName, and null if there is + * no such attribute otherwise. + */ + getAttributeNS(namespace: string | null, localName: string): string | null; + /** + * Returns the qualified names of all element's attributes. + * Can contain duplicates. + */ + getAttributeNames(): string[]; getAttributeNode(name: string): Attr | null; getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getBoundingClientRect(): ClientRect | DOMRect; getClientRects(): ClientRectList | DOMRectList; - getElementsByClassName(classNames: string): NodeListOf; - getElementsByTagName(name: K): NodeListOf; - getElementsByTagName(name: K): NodeListOf; - getElementsByTagName(name: string): NodeListOf; + getElementsByClassName(classNames: string): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: K): HTMLCollectionOf; + getElementsByTagName(qualifiedName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf; getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf; - hasAttribute(name: string): boolean; - hasAttributeNS(namespaceURI: string, localName: string): boolean; + /** + * Returns true if element has an attribute whose qualified name is qualifiedName, and false otherwise. + */ + hasAttribute(qualifiedName: string): boolean; + /** + * Returns true if element has an attribute whose namespace is namespace and local name is localName. + */ + hasAttributeNS(namespace: string | null, localName: string): boolean; + /** + * Returns true if element has attributes, and false otherwise. + */ hasAttributes(): boolean; hasPointerCapture(pointerId: number): boolean; insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null; insertAdjacentHTML(where: InsertPosition, html: string): void; insertAdjacentText(where: InsertPosition, text: string): void; + /** + * Returns true if matching selectors against element's root yields element, and false otherwise. + */ matches(selectors: string): boolean; msGetRegionContent(): any; - msGetUntransformedBounds(): ClientRect; - msMatchesSelector(selectors: string): boolean; - msReleasePointerCapture(pointerId: number): void; - msSetPointerCapture(pointerId: number): void; - msZoomTo(args: MsZoomToOptions): void; releasePointerCapture(pointerId: number): void; + /** + * Removes element's first attribute whose qualified name is qualifiedName. + */ removeAttribute(qualifiedName: string): void; - removeAttributeNS(namespaceURI: string, localName: string): void; - removeAttributeNode(oldAttr: Attr): Attr; - requestFullscreen(): void; - requestPointerLock(): void; + /** + * Removes element's attribute whose namespace is namespace and local name is localName. + */ + removeAttributeNS(namespace: string | null, localName: string): void; + removeAttributeNode(attr: Attr): Attr; + /** + * Displays element fullscreen and resolves promise when done. + */ + requestFullscreen(): Promise; scroll(options?: ScrollToOptions): void; scroll(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; @@ -5130,14 +4787,24 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNod scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void; scrollTo(options?: ScrollToOptions): void; scrollTo(x: number, y: number): void; + /** + * Sets the value of element's first attribute whose qualified name is qualifiedName to value. + */ setAttribute(qualifiedName: string, value: string): void; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; - setAttributeNode(newAttr: Attr): Attr; - setAttributeNodeNS(newAttr: Attr): Attr; + /** + * Sets the value of element's attribute whose namespace is namespace and local name is localName to value. + */ + setAttributeNS(namespace: string | null, qualifiedName: string, value: string): void; + setAttributeNode(attr: Attr): Attr | null; + setAttributeNodeNS(attr: Attr): Attr | null; setPointerCapture(pointerId: number): void; + /** + * If force is not given, "toggles" qualifiedName, removing it if it is + * present and adding it if it is not present. If force is true, adds qualifiedName. If force is false, removes qualifiedName. + * Returns true if qualifiedName is now present, and false otherwise. + */ + toggleAttribute(qualifiedName: string, force?: boolean): boolean; webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): void; - webkitRequestFullscreen(): void; addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5153,20 +4820,14 @@ interface ElementCSSInlineStyle { readonly style: CSSStyleDeclaration; } -interface ElementCreationOptions { - is?: string; -} - -interface ElementDefinitionOptions { - extends: string; +interface ElementContentEditable { + contentEditable: string; + inputMode: string; + readonly isContentEditable: boolean; } -interface ElementTraversal { - readonly childElementCount: number; - readonly firstElementChild: Element | null; - readonly lastElementChild: Element | null; - readonly nextElementSibling: Element | null; - readonly previousElementSibling: Element | null; +interface ElementCreationOptions { + is?: string; } interface ErrorEvent extends Event { @@ -5175,32 +4836,65 @@ interface ErrorEvent extends Event { readonly filename: string; readonly lineno: number; readonly message: string; - initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; } declare var ErrorEvent: { prototype: ErrorEvent; - new(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; + new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent; }; interface Event { + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + */ readonly bubbles: boolean; cancelBubble: boolean; readonly cancelable: boolean; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + */ readonly composed: boolean; + /** + * Returns the object whose event listener's callback is currently being + * invoked. + */ readonly currentTarget: EventTarget | null; readonly defaultPrevented: boolean; readonly eventPhase: number; + /** + * Returns true if event was dispatched by the user agent, and + * false otherwise. + */ readonly isTrusted: boolean; returnValue: boolean; readonly srcElement: Element | null; + /** + * Returns the object to which event is dispatched (its target). + */ readonly target: EventTarget | null; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to + * the time origin. + */ readonly timeStamp: number; + /** + * Returns the type of event, e.g. + * "click", "hashchange", or + * "submit". + */ readonly type: string; - deepPath(): EventTarget[]; + composedPath(): EventTarget[]; initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; preventDefault(): void; + /** + * Invoking this method prevents event from reaching + * any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any + * other objects. + */ stopImmediatePropagation(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + */ stopPropagation(): void; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; @@ -5210,7 +4904,7 @@ interface Event { declare var Event: { prototype: Event; - new(typeArg: string, eventInitDict?: EventInit): Event; + new(type: string, eventInitDict?: EventInit): Event; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; @@ -5244,9 +4938,26 @@ interface EventSourceInit { } interface EventTarget { + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * The options argument sets listener-specific options. For compatibility this can be a + * boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in §2.8 Observing event listeners. + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will + * be removed. + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + */ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; - dispatchEvent(evt: Event): boolean; - removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; + /** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ + dispatchEvent(event: Event): boolean; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + */ + removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; } declare var EventTarget: { @@ -5464,12 +5175,57 @@ interface GetSVGDocument { } interface GlobalEventHandlersEventMap { + "abort": UIEvent; "animationcancel": AnimationEvent; "animationend": AnimationEvent; "animationiteration": AnimationEvent; "animationstart": AnimationEvent; + "auxclick": Event; + "blur": FocusEvent; + "cancel": Event; + "canplay": Event; + "canplaythrough": Event; + "change": Event; + "click": MouseEvent; + "close": Event; + "contextmenu": MouseEvent; + "cuechange": Event; + "dblclick": MouseEvent; + "drag": DragEvent; + "dragend": DragEvent; + "dragenter": DragEvent; + "dragexit": Event; + "dragleave": DragEvent; + "dragover": DragEvent; + "dragstart": DragEvent; + "drop": DragEvent; + "durationchange": Event; + "emptied": Event; + "ended": Event; + "error": ErrorEvent; + "focus": FocusEvent; "gotpointercapture": PointerEvent; + "input": Event; + "invalid": Event; + "keydown": KeyboardEvent; + "keypress": KeyboardEvent; + "keyup": KeyboardEvent; + "load": Event; + "loadeddata": Event; + "loadedmetadata": Event; + "loadend": ProgressEvent; + "loadstart": Event; "lostpointercapture": PointerEvent; + "mousedown": MouseEvent; + "mouseenter": MouseEvent; + "mouseleave": MouseEvent; + "mousemove": MouseEvent; + "mouseout": MouseEvent; + "mouseover": MouseEvent; + "mouseup": MouseEvent; + "pause": Event; + "play": Event; + "playing": Event; "pointercancel": PointerEvent; "pointerdown": PointerEvent; "pointerenter": PointerEvent; @@ -5478,6 +5234,20 @@ interface GlobalEventHandlersEventMap { "pointerout": PointerEvent; "pointerover": PointerEvent; "pointerup": PointerEvent; + "progress": ProgressEvent; + "ratechange": Event; + "reset": Event; + "resize": UIEvent; + "scroll": UIEvent; + "securitypolicyviolation": SecurityPolicyViolationEvent; + "seeked": Event; + "seeking": Event; + "select": UIEvent; + "stalled": Event; + "submit": Event; + "suspend": Event; + "timeupdate": Event; + "toggle": Event; "touchcancel": TouchEvent; "touchend": TouchEvent; "touchmove": TouchEvent; @@ -5486,16 +5256,195 @@ interface GlobalEventHandlersEventMap { "transitionend": TransitionEvent; "transitionrun": TransitionEvent; "transitionstart": TransitionEvent; + "volumechange": Event; + "waiting": Event; "wheel": WheelEvent; } interface GlobalEventHandlers { + /** + * Fires when the user aborts the download. + * @param ev The event. + */ + onabort: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; onanimationcancel: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; onanimationend: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; onanimationiteration: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; onanimationstart: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null; + onauxclick: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ + onblur: ((this: GlobalEventHandlers, ev: FocusEvent) => any) | null; + oncancel: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ + oncanplay: ((this: GlobalEventHandlers, ev: Event) => any) | null; + oncanplaythrough: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ + onchange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ + onclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + onclose: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ + oncontextmenu: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + oncuechange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ + ondblclick: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ + ondrag: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ + ondragend: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ + ondragenter: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + ondragexit: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ + ondragleave: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ + ondragover: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ + ondragstart: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + ondrop: ((this: GlobalEventHandlers, ev: DragEvent) => any) | null; + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ + ondurationchange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ + onemptied: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the end of playback is reached. + * @param ev The event + */ + onended: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when an error occurs during object loading. + * @param ev The event. + */ + onerror: ErrorEventHandler; + /** + * Fires when the object receives focus. + * @param ev The event. + */ + onfocus: ((this: GlobalEventHandlers, ev: FocusEvent) => any) | null; ongotpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + oninput: ((this: GlobalEventHandlers, ev: Event) => any) | null; + oninvalid: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + */ + onkeydown: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null; + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ + onkeypress: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + */ + onkeyup: ((this: GlobalEventHandlers, ev: KeyboardEvent) => any) | null; + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ + onload: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ + onloadeddata: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ + onloadedmetadata: ((this: GlobalEventHandlers, ev: Event) => any) | null; + onloadend: ((this: GlobalEventHandlers, ev: ProgressEvent) => any) | null; + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ + onloadstart: ((this: GlobalEventHandlers, ev: Event) => any) | null; onlostpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ + onmousedown: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + onmouseenter: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + onmouseleave: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ + onmousemove: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ + onmouseout: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ + onmouseover: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ + onmouseup: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null; + /** + * Occurs when playback is paused. + * @param ev The event. + */ + onpause: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the play method is requested. + * @param ev The event. + */ + onplay: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ + onplaying: ((this: GlobalEventHandlers, ev: Event) => any) | null; onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; @@ -5504,6 +5453,60 @@ interface GlobalEventHandlers { onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null; + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ + onprogress: ((this: GlobalEventHandlers, ev: ProgressEvent) => any) | null; + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ + onratechange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the user resets a form. + * @param ev The event. + */ + onreset: ((this: GlobalEventHandlers, ev: Event) => any) | null; + onresize: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ + onscroll: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; + onsecuritypolicyviolation: ((this: GlobalEventHandlers, ev: SecurityPolicyViolationEvent) => any) | null; + /** + * Occurs when the seek operation ends. + * @param ev The event. + */ + onseeked: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when the current playback position is moved. + * @param ev The event. + */ + onseeking: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Fires when the current selection changes. + * @param ev The event. + */ + onselect: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null; + /** + * Occurs when the download has stopped. + * @param ev The event. + */ + onstalled: ((this: GlobalEventHandlers, ev: Event) => any) | null; + onsubmit: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ + onsuspend: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs to indicate the current playback position. + * @param ev The event. + */ + ontimeupdate: ((this: GlobalEventHandlers, ev: Event) => any) | null; + ontoggle: ((this: GlobalEventHandlers, ev: Event) => any) | null; ontouchcancel: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null; ontouchend: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null; ontouchmove: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null; @@ -5512,6 +5515,16 @@ interface GlobalEventHandlers { ontransitionend: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; ontransitionrun: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; ontransitionstart: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null; + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ + onvolumechange: ((this: GlobalEventHandlers, ev: Event) => any) | null; + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ + onwaiting: ((this: GlobalEventHandlers, ev: Event) => any) | null; onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null; addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -5520,7 +5533,7 @@ interface GlobalEventHandlers { } interface GlobalFetch { - fetch(input?: Request | string, init?: RequestInit): Promise; + fetch(input: RequestInfo, init?: RequestInit): Promise; } interface HTMLAllCollection { @@ -5545,7 +5558,6 @@ declare var HTMLAllCollection: { }; interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { - Methods: string; /** * Sets or retrieves the character set used to encode the object. */ @@ -5561,14 +5573,13 @@ interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { * Sets or retrieves the language code of the object. */ hreflang: string; - readonly mimeType: string; /** * Sets or retrieves the shape of the object. */ /** @deprecated */ name: string; - readonly nameProp: string; - readonly protocolLong: string; + ping: string; + referrerPolicy: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ @@ -5593,7 +5604,6 @@ interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils { */ text: string; type: string; - urn: string; addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5670,6 +5680,8 @@ interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils { */ /** @deprecated */ noHref: boolean; + ping: string; + referrerPolicy: string; rel: string; readonly relList: DOMTokenList; /** @@ -5691,14 +5703,6 @@ declare var HTMLAreaElement: { new(): HTMLAreaElement; }; -interface HTMLAreasCollection extends HTMLCollectionBase { -} - -declare var HTMLAreasCollection: { - prototype: HTMLAreasCollection; - new(): HTMLAreasCollection; -}; - interface HTMLAudioElement extends HTMLMediaElement { addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -5771,13 +5775,7 @@ declare var HTMLBaseFontElement: { }; interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { - "blur": FocusEvent; - "error": ErrorEvent; - "focus": FocusEvent; - "load": Event; "orientationchange": Event; - "resize": UIEvent; - "scroll": UIEvent; } interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { @@ -5792,8 +5790,8 @@ interface HTMLBodyElement extends HTMLElement, WindowEventHandlers { link: string; /** @deprecated */ noWrap: boolean; + /** @deprecated */ onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null; - onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null; /** @deprecated */ text: string; /** @deprecated */ @@ -5898,19 +5896,15 @@ interface HTMLCanvasElement extends HTMLElement { * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); */ - getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; + getContext(contextId: "2d", contextAttributes?: CanvasRenderingContext2DSettings): CanvasRenderingContext2D | null; getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; - /** - * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. - */ - msToBlob(): Blob; - toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void; + toBlob(callback: BlobCallback, type?: string, quality?: any): void; /** * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ - toDataURL(type?: string, ...args: any[]): string; + toDataURL(type?: string, quality?: any): string; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5930,7 +5924,7 @@ interface HTMLCollectionBase { /** * Retrieves an object from various collections. */ - item(index: number): Element; + item(index: number): Element | null; [index: number]: Element; } @@ -5947,9 +5941,8 @@ declare var HTMLCollection: { }; interface HTMLCollectionOf extends HTMLCollectionBase { - item(index: number): T; - namedItem(name: string): T; - forEach(callbackfn: (value: T, key: number, parent: HTMLCollectionOf) => void, thisArg?: any): void; + item(index: number): T | null; + namedItem(name: string): T | null; [index: number]: T; } @@ -6043,10 +6036,6 @@ interface HTMLDivElement extends HTMLElement { */ /** @deprecated */ align: string; - /** - * Sets or retrieves whether the browser automatically performs wordwrap. - */ - noWrap: boolean; addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -6070,168 +6059,27 @@ declare var HTMLDocument: { new(): HTMLDocument; }; -interface HTMLElementEventMap extends ElementEventMap { - "abort": UIEvent; - "activate": Event; - "beforeactivate": Event; - "beforecopy": Event; - "beforecut": Event; - "beforedeactivate": Event; - "beforepaste": Event; - "blur": FocusEvent; - "canplay": Event; - "canplaythrough": Event; - "change": Event; - "click": MouseEvent; - "contextmenu": PointerEvent; - "copy": ClipboardEvent; - "cuechange": Event; - "cut": ClipboardEvent; - "dblclick": MouseEvent; - "deactivate": Event; - "drag": DragEvent; - "dragend": DragEvent; - "dragenter": DragEvent; - "dragleave": DragEvent; - "dragover": DragEvent; - "dragstart": DragEvent; - "drop": DragEvent; - "durationchange": Event; - "emptied": Event; - "ended": Event; - "error": ErrorEvent; - "focus": FocusEvent; - "input": Event; - "invalid": Event; - "keydown": KeyboardEvent; - "keypress": KeyboardEvent; - "keyup": KeyboardEvent; - "load": Event; - "loadeddata": Event; - "loadedmetadata": Event; - "loadstart": Event; - "mousedown": MouseEvent; - "mouseenter": MouseEvent; - "mouseleave": MouseEvent; - "mousemove": MouseEvent; - "mouseout": MouseEvent; - "mouseover": MouseEvent; - "mouseup": MouseEvent; - "mousewheel": WheelEvent; - "MSContentZoom": Event; - "MSManipulationStateChanged": Event; - "paste": ClipboardEvent; - "pause": Event; - "play": Event; - "playing": Event; - "progress": ProgressEvent; - "ratechange": Event; - "reset": Event; - "scroll": UIEvent; - "seeked": Event; - "seeking": Event; - "select": UIEvent; - "selectstart": Event; - "stalled": Event; - "submit": Event; - "suspend": Event; - "timeupdate": Event; - "volumechange": Event; - "waiting": Event; +interface HTMLElementEventMap extends ElementEventMap, GlobalEventHandlersEventMap, DocumentAndElementEventHandlersEventMap { } -interface HTMLElement extends Element, ElementCSSInlineStyle { +interface HTMLElement extends Element, GlobalEventHandlers, DocumentAndElementEventHandlers, ElementContentEditable, HTMLOrSVGElement, ElementCSSInlineStyle { accessKey: string; - contentEditable: string; - readonly dataset: DOMStringMap; + readonly accessKeyLabel: string; + autocapitalize: string; dir: string; draggable: boolean; hidden: boolean; - hideFocus: boolean; innerText: string; - readonly isContentEditable: boolean; lang: string; readonly offsetHeight: number; readonly offsetLeft: number; - readonly offsetParent: Element; + readonly offsetParent: Element | null; readonly offsetTop: number; readonly offsetWidth: number; - onabort: ((this: HTMLElement, ev: UIEvent) => any) | null; - onactivate: ((this: HTMLElement, ev: Event) => any) | null; - onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null; - onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null; - onbeforecut: ((this: HTMLElement, ev: Event) => any) | null; - onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null; - onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null; - onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null; - oncanplay: ((this: HTMLElement, ev: Event) => any) | null; - oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null; - onchange: ((this: HTMLElement, ev: Event) => any) | null; - onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; - oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null; - oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; - oncuechange: ((this: HTMLElement, ev: Event) => any) | null; - oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; - ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null; - ondeactivate: ((this: HTMLElement, ev: Event) => any) | null; - ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null; - ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null; - ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null; - ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null; - ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null; - ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null; - ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null; - ondurationchange: ((this: HTMLElement, ev: Event) => any) | null; - onemptied: ((this: HTMLElement, ev: Event) => any) | null; - onended: ((this: HTMLElement, ev: Event) => any) | null; - onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null; - onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null; - oninput: ((this: HTMLElement, ev: Event) => any) | null; - oninvalid: ((this: HTMLElement, ev: Event) => any) | null; - onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; - onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; - onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null; - onload: ((this: HTMLElement, ev: Event) => any) | null; - onloadeddata: ((this: HTMLElement, ev: Event) => any) | null; - onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null; - onloadstart: ((this: HTMLElement, ev: Event) => any) | null; - onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null; - onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null; - onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null; - onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null; - onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null; - onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null; - onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null; - onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null; - onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null; - onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null; - onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null; - onpause: ((this: HTMLElement, ev: Event) => any) | null; - onplay: ((this: HTMLElement, ev: Event) => any) | null; - onplaying: ((this: HTMLElement, ev: Event) => any) | null; - onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null; - onratechange: ((this: HTMLElement, ev: Event) => any) | null; - onreset: ((this: HTMLElement, ev: Event) => any) | null; - onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null; - onseeked: ((this: HTMLElement, ev: Event) => any) | null; - onseeking: ((this: HTMLElement, ev: Event) => any) | null; - onselect: ((this: HTMLElement, ev: UIEvent) => any) | null; - onselectstart: ((this: HTMLElement, ev: Event) => any) | null; - onstalled: ((this: HTMLElement, ev: Event) => any) | null; - onsubmit: ((this: HTMLElement, ev: Event) => any) | null; - onsuspend: ((this: HTMLElement, ev: Event) => any) | null; - ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null; - onvolumechange: ((this: HTMLElement, ev: Event) => any) | null; - onwaiting: ((this: HTMLElement, ev: Event) => any) | null; - outerText: string; spellcheck: boolean; - tabIndex: number; title: string; - blur(): void; + translate: boolean; click(): void; - dragDrop(): boolean; - focus(): void; - msGetInputContext(): MSInputMethodContext; addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -6428,16 +6276,6 @@ interface HTMLFormElement extends HTMLElement { * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; - /** - * Retrieves a form object or an object from an elements collection. - * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. - * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. - */ - item(name?: any, index?: any): any; - /** - * Retrieves a form object or an object from an elements collection. - */ - namedItem(name: string): any; reportValidity(): boolean; /** * Fires when the user resets a form. @@ -6451,6 +6289,7 @@ interface HTMLFormElement extends HTMLElement { addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; + [index: number]: Element; [name: string]: any; } @@ -6469,7 +6308,7 @@ interface HTMLFrameElement extends HTMLElement { * Retrieves the object of the specified. */ /** @deprecated */ - readonly contentWindow: Window | null; + readonly contentWindow: WindowProxy | null; /** * Sets or retrieves whether to display a border for the frame. */ @@ -6521,6 +6360,9 @@ declare var HTMLFrameElement: { new(): HTMLFrameElement; }; +interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { +} + interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { /** * Sets or retrieves the frame widths of the object. @@ -6532,11 +6374,9 @@ interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers { */ /** @deprecated */ rows: string; - addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } @@ -6577,8 +6417,6 @@ declare var HTMLHRElement: { }; interface HTMLHeadElement extends HTMLElement { - /** @deprecated */ - profile: string; addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -6629,16 +6467,13 @@ interface HTMLHyperlinkElementUtils { host: string; hostname: string; href: string; - origin: string; + readonly origin: string; + password: string; pathname: string; port: string; protocol: string; search: string; - toString(): string; -} - -interface HTMLIFrameElementEventMap extends HTMLElementEventMap { - "load": Event; + username: string; } interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { @@ -6703,9 +6538,9 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; - addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } @@ -6756,19 +6591,6 @@ interface HTMLImageElement extends HTMLElement { longDesc: string; /** @deprecated */ lowsrc: string; - /** - * Gets or sets whether the DLNA PlayTo device is available. - */ - msPlayToDisabled: boolean; - msPlayToPreferredSourceUri: string; - /** - * Gets or sets the primary DLNA PlayTo device. - */ - msPlayToPrimary: boolean; - /** - * Gets the source associated with the media element for use by the PlayToManager. - */ - readonly msPlayToSource: any; /** * Sets or retrieves the name of the object. */ @@ -6782,6 +6604,7 @@ interface HTMLImageElement extends HTMLElement { * The original width of the image resource before sizing. */ readonly naturalWidth: number; + referrerPolicy: string; sizes: string; /** * The address or URL of the a media resource that is to be considered. @@ -6803,7 +6626,7 @@ interface HTMLImageElement extends HTMLElement { width: number; readonly x: number; readonly y: number; - msGetAsCastingSource(): any; + decode(): Promise; addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -6849,6 +6672,7 @@ interface HTMLInputElement extends HTMLElement { * Sets or retrieves the initial contents of the object. */ defaultValue: string; + dirName: string; disabled: boolean; /** * Returns a FileList object on a file type input object. @@ -6883,6 +6707,7 @@ interface HTMLInputElement extends HTMLElement { */ height: number; indeterminate: boolean; + readonly labels: NodeListOf | null; /** * Specifies the ID of a pre-defined datalist of options for an input element. */ @@ -6965,7 +6790,6 @@ interface HTMLInputElement extends HTMLElement { * Returns the input field value as a number. */ valueAsNumber: number; - webkitdirectory: boolean; /** * Sets or retrieves the width of the object. */ @@ -6978,6 +6802,7 @@ interface HTMLInputElement extends HTMLElement { * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; + reportValidity(): boolean; /** * Makes the selection equal to the current object. */ @@ -6987,6 +6812,8 @@ interface HTMLInputElement extends HTMLElement { * @param error Sets a custom error message that is displayed when a form is submitted. */ setCustomValidity(error: string): void; + setRangeText(replacement: string): void; + setRangeText(replacement: string, start: number, end: number, selectionMode?: SelectionMode): void; /** * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. @@ -7034,7 +6861,7 @@ declare var HTMLLIElement: { }; interface HTMLLabelElement extends HTMLElement { - readonly control: HTMLInputElement | null; + readonly control: HTMLElement | null; /** * Retrieves a reference to the form that the object is embedded in. */ @@ -7073,13 +6900,13 @@ declare var HTMLLegendElement: { }; interface HTMLLinkElement extends HTMLElement, LinkStyle { + as: string; /** * Sets or retrieves the character set used to encode the object. */ /** @deprecated */ charset: string; crossOrigin: string | null; - /** @deprecated */ disabled: boolean; /** * Sets or retrieves a destination URL or an anchor point. @@ -7089,12 +6916,12 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { * Sets or retrieves the language code of the object. */ hreflang: string; - import?: Document; integrity: string; /** * Sets or retrieves the media type. */ media: string; + referrerPolicy: string; /** * Sets or retrieves the relationship between the object and the destination of the link. */ @@ -7105,6 +6932,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { */ /** @deprecated */ rev: string; + readonly sizes: DOMTokenList; /** * Sets or retrieves the window or frame at which to target content. */ @@ -7141,7 +6969,7 @@ interface HTMLMapElement extends HTMLElement { /** * Retrieves a collection of the area objects defined for the given map object. */ - readonly areas: HTMLAreasCollection; + readonly areas: HTMLCollection; /** * Sets or retrieves the name of the object. */ @@ -7406,7 +7234,6 @@ declare var HTMLMediaElement: { interface HTMLMenuElement extends HTMLElement { /** @deprecated */ compact: boolean; - type: string; addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7419,11 +7246,6 @@ declare var HTMLMenuElement: { }; interface HTMLMetaElement extends HTMLElement { - /** - * Sets or retrieves the character set used to encode the object. - */ - /** @deprecated */ - charset: string; /** * Gets or sets meta-information to associate with httpEquiv or name. */ @@ -7441,11 +7263,6 @@ interface HTMLMetaElement extends HTMLElement { */ /** @deprecated */ scheme: string; - /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. - */ - /** @deprecated */ - url: string; addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7499,6 +7316,7 @@ declare var HTMLModElement: { interface HTMLOListElement extends HTMLElement { /** @deprecated */ compact: boolean; + reversed: boolean; /** * The starting number. */ @@ -7621,6 +7439,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether a form will validate when it is submitted, without having to submit it. */ checkValidity(): boolean; + reportValidity(): boolean; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. @@ -7720,7 +7539,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { * This method will throw a "HierarchyRequestError" DOMException if * element is an ancestor of the element into which it is to be inserted. */ - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; /** * Removes the item with index index from the collection. */ @@ -7732,6 +7551,14 @@ declare var HTMLOptionsCollection: { new(): HTMLOptionsCollection; }; +interface HTMLOrSVGElement { + readonly dataset: DOMStringMap; + nonce: string; + tabIndex: number; + blur(): void; + focus(options?: FocusOptions): void; +} + interface HTMLOutputElement extends HTMLElement { defaultValue: string; readonly form: HTMLFormElement | null; @@ -7763,7 +7590,6 @@ interface HTMLParagraphElement extends HTMLElement { */ /** @deprecated */ align: string; - clear: string; addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7899,6 +7725,7 @@ interface HTMLScriptElement extends HTMLElement { htmlFor: string; integrity: string; noModule: boolean; + referrerPolicy: string; /** * Retrieves the URL to an external file that contains the source code or data. */ @@ -7985,7 +7812,7 @@ interface HTMLSelectElement extends HTMLElement { * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. */ - add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; + add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -8017,7 +7844,7 @@ interface HTMLSelectElement extends HTMLElement { addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; - [index: number]: Element; + [name: number]: HTMLOptionElement | HTMLOptGroupElement; } declare var HTMLSelectElement: { @@ -8027,6 +7854,7 @@ declare var HTMLSelectElement: { interface HTMLSlotElement extends HTMLElement { name: string; + assignedElements(options?: AssignedNodesOptions): Element[]; assignedNodes(options?: AssignedNodesOptions): Node[]; addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -8034,13 +7862,16 @@ interface HTMLSlotElement extends HTMLElement { removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } +declare var HTMLSlotElement: { + prototype: HTMLSlotElement; + new(): HTMLSlotElement; +}; + interface HTMLSourceElement extends HTMLElement { /** * Gets or sets the intended media type of the media source. */ media: string; - /** @deprecated */ - msKeySystem: string; sizes: string; /** * The address or URL of the a media resource that is to be considered. @@ -8075,8 +7906,6 @@ declare var HTMLSpanElement: { }; interface HTMLStyleElement extends HTMLElement, LinkStyle { - /** @deprecated */ - disabled: boolean; /** * Sets or retrieves the media type. */ @@ -8097,18 +7926,6 @@ declare var HTMLStyleElement: { new(): HTMLStyleElement; }; -interface HTMLSummaryElement extends HTMLElement { - addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var HTMLSummaryElement: { - prototype: HTMLSummaryElement; - new(): HTMLSummaryElement; -}; - interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. @@ -8326,7 +8143,7 @@ interface HTMLTableElement extends HTMLElement { * Removes the specified row (tr) from the element and from the rows collection. * @param index Number that specifies the zero-based position in the rows collection of the row to remove. */ - deleteRow(index?: number): void; + deleteRow(index: number): void; /** * Deletes the tFoot element and its contents from the table. */ @@ -8394,7 +8211,7 @@ interface HTMLTableRowElement extends HTMLElement { * Removes the specified cell from the table row, as well as from the cells collection. * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. */ - deleteCell(index?: number): void; + deleteCell(index: number): void; /** * Creates a new cell in the table row, and adds the cell to the cells collection. * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. @@ -8431,7 +8248,7 @@ interface HTMLTableSectionElement extends HTMLElement { * Removes the specified row (tr) from the element and from the rows collection. * @param index Number that specifies the zero-based position in the rows collection of the row to remove. */ - deleteRow(index?: number): void; + deleteRow(index: number): void; /** * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. @@ -8744,11 +8561,11 @@ interface History { readonly length: number; scrollRestoration: ScrollRestoration; readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(data: any, title?: string, url?: string | null): void; - replaceState(data: any, title?: string, url?: string | null): void; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; } declare var History: { @@ -8804,13 +8621,13 @@ interface IDBCursor { * Delete the record pointed at by the cursor with a new value. * If successful, request's result will be undefined. */ - delete(): IDBRequest; + delete(): IDBRequest; /** * Updated the record pointed at by the cursor with a new value. * Throws a "DataError" DOMException if the effective object store uses in-line keys and the key would have changed. * If successful, request's result will be the record's key. */ - update(value: any): IDBRequest; + update(value: any): IDBRequest; } declare var IDBCursor: { @@ -8936,40 +8753,40 @@ interface IDBIndex { * If successful, request's result will be the * count. */ - count(key?: IDBValidKey | IDBKeyRange): IDBRequest; + count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the value of the first record matching the * given key or key range in query. * If successful, request's result will be the value, or undefined if there was no matching record. */ - get(key: IDBValidKey | IDBKeyRange): IDBRequest; + get(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). * If successful, request's result will be an Array of the values. */ - getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). * If successful, request's result will be an Array of the keys. */ - getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the * given key or key range in query. * If successful, request's result will be the key, or undefined if there was no matching record. */ - getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; + getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Opens a cursor over the records matching query, * ordered by direction. If query is null, all records in index are matched. * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records. */ - openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched. * If successful, request's result will be an IDBCursor, or null if there were no matching records. */ - openKeyCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -9048,19 +8865,19 @@ interface IDBObjectStore { * Returns the associated transaction. */ readonly transaction: IDBTransaction; - add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; + add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Deletes all records in store. * If successful, request's result will * be undefined. */ - clear(): IDBRequest; + clear(): IDBRequest; /** * Retrieves the number of records matching the * given key or key range in query. * If successful, request's result will be the count. */ - count(key?: IDBValidKey | IDBKeyRange): IDBRequest; + count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be * satisfied with the data already in store the upgrade @@ -9075,7 +8892,7 @@ interface IDBObjectStore { * If successful, request's result will * be undefined. */ - delete(key: IDBValidKey | IDBKeyRange): IDBRequest; + delete(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Deletes the index in store with the given name. * Throws an "InvalidStateError" DOMException if not called within an upgrade @@ -9087,41 +8904,41 @@ interface IDBObjectStore { * given key or key range in query. * If successful, request's result will be the value, or undefined if there was no matching record. */ - get(query: IDBValidKey | IDBKeyRange): IDBRequest; + get(query: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the * given key or key range in query (up to count if given). * If successful, request's result will * be an Array of the values. */ - getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; /** * Retrieves the keys of records matching the * given key or key range in query (up to count if given). * If successful, request's result will * be an Array of the keys. */ - getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the * given key or key range in query. * If successful, request's result will be the key, or undefined if there was no matching record. */ - getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; + getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; index(name: string): IDBIndex; /** * Opens a cursor over the records matching query, * ordered by direction. If query is null, all records in store are matched. * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records. */ - openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched. * If successful, request's result will be an IDBCursor pointing at the first matching record, or * null if there were no matching records. */ - openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; - put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; + openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; } declare var IDBObjectStore: { @@ -9134,7 +8951,7 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "upgradeneeded": IDBVersionChangeEvent; } -interface IDBOpenDBRequest extends IDBRequest { +interface IDBOpenDBRequest extends IDBRequest { onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -9153,14 +8970,14 @@ interface IDBRequestEventMap { "success": Event; } -interface IDBRequest extends EventTarget { +interface IDBRequest extends EventTarget { /** * When a request is completed, returns the error (a DOMException), or null if the request succeeded. Throws * a "InvalidStateError" DOMException if the request is still pending. */ readonly error: DOMException | null; - onerror: ((this: IDBRequest, ev: Event) => any) | null; - onsuccess: ((this: IDBRequest, ev: Event) => any) | null; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; /** * Returns "pending" until a request is complete, * then returns "done". @@ -9171,7 +8988,7 @@ interface IDBRequest extends EventTarget { * or undefined if the request failed. Throws a * "InvalidStateError" DOMException if the request is still pending. */ - readonly result: any; + readonly result: T; /** * Returns the IDBObjectStore, IDBIndex, or IDBCursor the request was made against, or null if is was an open * request. @@ -9182,9 +8999,9 @@ interface IDBRequest extends EventTarget { * If this as an open request, then it returns an upgrade transaction while it is running, or null otherwise. */ readonly transaction: IDBTransaction | null; - addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } @@ -9264,11 +9081,27 @@ declare var IIRFilterNode: { }; interface ImageBitmap { + /** + * Returns the intrinsic height of the image, in CSS + * pixels. + */ readonly height: number; + /** + * Returns the intrinsic width of the image, in CSS + * pixels. + */ readonly width: number; + /** + * Releases imageBitmap's underlying bitmap data. + */ close(): void; } +declare var ImageBitmap: { + prototype: ImageBitmap; + new(): ImageBitmap; +}; + interface ImageBitmapOptions { colorSpaceConversion?: "none" | "default"; imageOrientation?: "none" | "flipY"; @@ -9278,8 +9111,34 @@ interface ImageBitmapOptions { resizeWidth?: number; } +interface ImageBitmapRenderingContext { + /** + * Returns the canvas element that the context is bound to. + */ + readonly canvas: HTMLCanvasElement; + /** + * Replaces contents of the canvas element to which context + * is bound with a transparent black bitmap whose size corresponds to the width and height + * content attributes of the canvas element. + */ + transferFromImageBitmap(bitmap: ImageBitmap | null): void; +} + +declare var ImageBitmapRenderingContext: { + prototype: ImageBitmapRenderingContext; + new(): ImageBitmapRenderingContext; +}; + interface ImageData { + /** + * Returns the one-dimensional array containing the data in RGBA order, as integers in the + * range 0 to 255. + */ readonly data: Uint8ClampedArray; + /** + * Returns the actual dimensions of the data in the ImageData object, in + * pixels. + */ readonly height: number; readonly width: number; } @@ -9388,19 +9247,68 @@ declare var ListeningStateChangedEvent: { }; interface Location { + /** + * Returns a DOMStringList object listing the origins of the ancestor browsing contexts, from the parent browsing + * context to the top-level browsing context. + */ + readonly ancestorOrigins: DOMStringList; + /** + * Returns the Location object's URL's fragment (includes leading "#" if non-empty). + * Can be set, to navigate to the same URL with a changed fragment (ignores leading "#"). + */ hash: string; + /** + * Returns the Location object's URL's host and port (if different from the default + * port for the scheme). + * Can be set, to navigate to the same URL with a changed host and port. + */ host: string; + /** + * Returns the Location object's URL's host. + * Can be set, to navigate to the same URL with a changed host. + */ hostname: string; + /** + * Returns the Location object's URL. + * Can be set, to navigate to the given URL. + */ href: string; + /** + * Returns the Location object's URL's origin. + */ readonly origin: string; + /** + * Returns the Location object's URL's path. + * Can be set, to navigate to the same URL with a changed path. + */ pathname: string; + /** + * Returns the Location object's URL's port. + * Can be set, to navigate to the same URL with a changed port. + */ port: string; + /** + * Returns the Location object's URL's scheme. + * Can be set, to navigate to the same URL with a changed scheme. + */ protocol: string; + /** + * Returns the Location object's URL's query (includes leading "?" if non-empty). + * Can be set, to navigate to the same URL with a changed query (ignores leading "?"). + */ search: string; + /** + * Navigates to the given URL. + */ assign(url: string): void; + /** + * Reloads the current page. + */ reload(forcedReload?: boolean): void; + /** + * Removes the current page from the session history and navigates to the given URL. + */ replace(url: string): void; - toString(): string; } declare var Location: { @@ -9428,36 +9336,6 @@ declare var MSBlobBuilder: { new(): MSBlobBuilder; }; -interface MSCredentials { - getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; - makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): Promise; -} - -declare var MSCredentials: { - prototype: MSCredentials; - new(): MSCredentials; -}; - -interface MSDCCEvent extends Event { - readonly maxFr: number; - readonly maxFs: number; -} - -declare var MSDCCEvent: { - prototype: MSDCCEvent; - new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent; -}; - -interface MSDSHEvent extends Event { - readonly sources: number[]; - readonly timestamp: number; -} - -declare var MSDSHEvent: { - prototype: MSDSHEvent; - new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent; -}; - interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; readonly attestation: any; @@ -9836,11 +9714,22 @@ declare var MediaList: { new(): MediaList; }; -interface MediaQueryList { +interface MediaQueryListEventMap { + "change": MediaQueryListEvent; +} + +interface MediaQueryList extends EventTarget { readonly matches: boolean; readonly media: string; - addListener(listener: MediaQueryListListener): void; - removeListener(listener: MediaQueryListListener): void; + onchange: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null; + /** @deprecated */ + addListener(listener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null): void; + /** @deprecated */ + removeListener(listener: EventListenerOrEventListenerObject | null): void; + addEventListener(type: K, listener: (this: MediaQueryList, ev: MediaQueryListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: MediaQueryList, ev: MediaQueryListEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MediaQueryList: { @@ -9848,6 +9737,16 @@ declare var MediaQueryList: { new(): MediaQueryList; }; +interface MediaQueryListEvent extends Event { + readonly matches: boolean; + readonly media: string; +} + +declare var MediaQueryListEvent: { + prototype: MediaQueryListEvent; + new(type: string, eventInitDict?: MediaQueryListEventInit): MediaQueryListEvent; +}; + interface MediaSource extends EventTarget { readonly activeSourceBuffers: SourceBufferList; duration: number; @@ -10014,11 +9913,31 @@ declare var MessageChannel: { }; interface MessageEvent extends Event { + /** + * Returns the data of the message. + */ readonly data: any; + /** + * Returns the last event ID string, for + * server-sent events. + */ + readonly lastEventId: string; + /** + * Returns the origin of the message, for server-sent events and + * cross-document messaging. + */ readonly origin: string; + /** + * Returns the MessagePort array sent with the message, for cross-document + * messaging and channel messaging. + */ readonly ports: ReadonlyArray; - readonly source: MessageEventSource; - initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void; + /** + * Returns the WindowProxy of the source window, for cross-document + * messaging, and the MessagePort being attached, in the connect event fired at + * SharedWorkerGlobalScope objects. + */ + readonly source: MessageEventSource | null; } declare var MessageEvent: { @@ -10045,7 +9964,7 @@ interface MessagePort extends EventTarget { * transfer contains duplicate objects or port, or if message * could not be cloned. */ - postMessage(message: any, transfer?: any[]): void; + postMessage(message: any, transfer?: Transferable[]): void; /** * Begins dispatching messages received on the port. */ @@ -10144,7 +10063,40 @@ declare var MutationEvent: { interface MutationObserver { disconnect(): void; - observe(target: Node, options: MutationObserverInit): void; + /** + * Instructs the user agent to observe a given target (a node) and report any mutations based on + * the criteria given by options (an object). + * The options argument allows for setting mutation + * observation options via object members. These are the object members that + * can be used: + * childList + * Set to true if mutations to target's children are to be observed. + * attributes + * Set to true if mutations to target's attributes are to be observed. Can be omitted if attributeOldValue or attributeFilter is + * specified. + * characterData + * Set to true if mutations to target's data are to be observed. Can be omitted if characterDataOldValue is specified. + * subtree + * Set to true if mutations to not just target, but + * also target's descendants are to be + * observed. + * attributeOldValue + * Set to true if attributes is true or omitted + * and target's attribute value before the mutation + * needs to be recorded. + * characterDataOldValue + * Set to true if characterData is set to true or omitted and target's data before the mutation + * needs to be recorded. + * attributeFilter + * Set to a list of attribute local names (without namespace) if not all attribute mutations need to be + * observed and attributes is true + * or omitted. + */ + observe(target: Node, options?: MutationObserverInit): void; + /** + * Empties the record queue and + * returns what was in there. + */ takeRecords(): MutationRecord[]; } @@ -10155,13 +10107,41 @@ declare var MutationObserver: { interface MutationRecord { readonly addedNodes: NodeList; + /** + * Returns the local name of the + * changed attribute, and null otherwise. + */ readonly attributeName: string | null; + /** + * Returns the namespace of the + * changed attribute, and null otherwise. + */ readonly attributeNamespace: string | null; + /** + * Return the previous and next sibling respectively + * of the added or removed nodes, and null otherwise. + */ readonly nextSibling: Node | null; + /** + * The return value depends on type. For + * "attributes", it is the value of the + * changed attribute before the change. + * For "characterData", it is the data of the changed node before the change. For + * "childList", it is null. + */ readonly oldValue: string | null; readonly previousSibling: Node | null; + /** + * Return the nodes added and removed + * respectively. + */ readonly removedNodes: NodeList; readonly target: Node; + /** + * Returns "attributes" if it was an attribute mutation. + * "characterData" if it was a mutation to a CharacterData node. And + * "childList" if it was a mutation to the tree of nodes. + */ readonly type: MutationRecordType; } @@ -10199,7 +10179,7 @@ declare var NavigationPreloadManager: { new(): NavigationPreloadManager; }; -interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage, NavigatorStorage { +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage, NavigatorStorage, NavigatorAutomationInformation { readonly activeVRDisplays: ReadonlyArray; readonly authentication: WebAuthentication; readonly cookieEnabled: boolean; @@ -10228,6 +10208,10 @@ declare var Navigator: { new(): Navigator; }; +interface NavigatorAutomationInformation { + readonly webdriver: boolean; +} + interface NavigatorBeacon { sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean; } @@ -10274,33 +10258,104 @@ interface NavigatorUserMedia { } interface Node extends EventTarget { - readonly baseURI: string | null; - readonly childNodes: NodeListOf; - readonly firstChild: Node | null; + /** + * Returns node's node document's document base URL. + */ + readonly baseURI: string; + /** + * Returns the children. + */ + readonly childNodes: NodeListOf; + /** + * Returns the first child. + */ + readonly firstChild: ChildNode | null; + /** + * Returns true if node is connected and false otherwise. + */ readonly isConnected: boolean; - readonly lastChild: Node | null; - readonly localName: string | null; + /** + * Returns the last child. + */ + readonly lastChild: ChildNode | null; readonly namespaceURI: string | null; + /** + * Returns the next sibling. + */ readonly nextSibling: Node | null; + /** + * Returns a string appropriate for the type of node, as + * follows: + * Element + * Its HTML-uppercased qualified name. + * Attr + * Its qualified name. + * Text + * "#text". + * CDATASection + * "#cdata-section". + * ProcessingInstruction + * Its target. + * Comment + * "#comment". + * Document + * "#document". + * DocumentType + * Its name. + * DocumentFragment + * "#document-fragment". + */ readonly nodeName: string; readonly nodeType: number; nodeValue: string | null; - readonly ownerDocument: Document; + /** + * Returns the node document. + * Returns null for documents. + */ + readonly ownerDocument: Document | null; + /** + * Returns the parent element. + */ readonly parentElement: HTMLElement | null; - readonly parentNode: Node | null; + /** + * Returns the parent. + */ + readonly parentNode: Node & ParentNode | null; + /** + * Returns the previous sibling. + */ readonly previousSibling: Node | null; textContent: string | null; appendChild(newChild: T): T; + /** + * Returns a copy of node. If deep is true, the copy also includes the node's descendants. + */ cloneNode(deep?: boolean): Node; compareDocumentPosition(other: Node): number; - contains(child: Node): boolean; + /** + * Returns true if other is an inclusive descendant of node, and false otherwise. + */ + contains(other: Node | null): boolean; + /** + * Returns node's shadow-including root. + */ + getRootNode(options?: GetRootNodeOptions): Node; + /** + * Returns whether node has children. + */ hasChildNodes(): boolean; insertBefore(newChild: T, refChild: Node | null): T; - isDefaultNamespace(namespaceURI: string | null): boolean; - isEqualNode(arg: Node): boolean; - isSameNode(other: Node): boolean; + isDefaultNamespace(namespace: string | null): boolean; + /** + * Returns whether node and otherNode have the same properties. + */ + isEqualNode(otherNode: Node | null): boolean; + isSameNode(otherNode: Node | null): boolean; lookupNamespaceURI(prefix: string | null): string | null; - lookupPrefix(namespaceURI: string | null): string | null; + lookupPrefix(namespace: string | null): string | null; + /** + * Removes empty exclusive Text nodes and concatenates the data of remaining contiguous exclusive Text nodes into the first of their nodes. + */ normalize(): void; removeChild(oldChild: T): T; replaceChild(newChild: Node, oldChild: T): T; @@ -10371,9 +10426,9 @@ declare var NodeFilter: { }; interface NodeIterator { - /** @deprecated */ - readonly expandEntityReferences: boolean; readonly filter: NodeFilter | null; + readonly pointerBeforeReferenceNode: boolean; + readonly referenceNode: Node; readonly root: Node; readonly whatToShow: number; detach(): void; @@ -10387,8 +10442,14 @@ declare var NodeIterator: { }; interface NodeList { + /** + * Returns the number of nodes in the collection. + */ readonly length: number; - item(index: number): Node; + /** + * element = collection[index] + */ + item(index: number): Node | null; /** * Performs the specified action for each node in an list. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list. @@ -10424,6 +10485,26 @@ interface NodeSelector { querySelectorAll(selectors: string): NodeListOf; } +interface NonDocumentTypeChildNode { + /** + * Returns the first following sibling that + * is an element, and null otherwise. + */ + readonly nextElementSibling: Element | null; + /** + * Returns the first preceding sibling that + * is an element, and null otherwise. + */ + readonly previousElementSibling: Element | null; +} + +interface NonElementParentNode { + /** + * Returns the first element within node's descendants whose ID is elementId. + */ + getElementById(elementId: string): Element | null; +} + interface NotificationEventMap { "click": Event; "close": Event; @@ -10626,23 +10707,55 @@ declare var PannerNode: { interface ParentNode { readonly childElementCount: number; + /** + * Returns the child elements. + */ readonly children: HTMLCollection; + /** + * Returns the first child that is an element, and null otherwise. + */ readonly firstElementChild: Element | null; + /** + * Returns the last child that is an element, and null otherwise. + */ readonly lastElementChild: Element | null; + /** + * Inserts nodes after the last child of node, while replacing + * strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + append(...nodes: (Node | string)[]): void; + /** + * Inserts nodes before the first child of node, while + * replacing strings in nodes with equivalent Text nodes. + * Throws a "HierarchyRequestError" DOMException if the constraints of + * the node tree are violated. + */ + prepend(...nodes: (Node | string)[]): void; + /** + * Returns the first element that is a descendant of node that + * matches selectors. + */ querySelector(selectors: K): HTMLElementTagNameMap[K] | null; querySelector(selectors: K): SVGElementTagNameMap[K] | null; querySelector(selectors: string): E | null; + /** + * Returns all element descendants of node that + * match selectors. + */ querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: K): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } -interface Path2D extends CanvasPathMethods { +interface Path2D extends CanvasPath { + addPath(path: Path2D, transform?: DOMMatrix2DInit): void; } declare var Path2D: { prototype: Path2D; - new(d?: Path2D | string): Path2D; + new(path?: Path2D | string): Path2D; }; interface PaymentAddress { @@ -11042,7 +11155,7 @@ declare var ProgressEvent: { }; interface PromiseRejectionEvent extends Event { - readonly promise: PromiseLike; + readonly promise: Promise; readonly reason: any; } @@ -11475,7 +11588,7 @@ interface RTCRtpReceiver { declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(): RTCRtpReceiver; - getCapabilities(kind: string): RTCRtpCapabilities; + getCapabilities(kind: string): RTCRtpCapabilities | null; }; interface RTCRtpSender { @@ -11493,7 +11606,7 @@ interface RTCRtpSender { declare var RTCRtpSender: { prototype: RTCRtpSender; new(): RTCRtpSender; - getCapabilities(kind: string): RTCRtpCapabilities; + getCapabilities(kind: string): RTCRtpCapabilities | null; }; interface RTCRtpTransceiver { @@ -11630,25 +11743,32 @@ declare var RandomSource: { new(): RandomSource; }; -interface Range { - readonly collapsed: boolean; +interface Range extends AbstractRange { + /** + * Returns the node, furthest away from + * the document, that is an ancestor of both range's start node and end node. + */ readonly commonAncestorContainer: Node; - readonly endContainer: Node; - readonly endOffset: number; - readonly startContainer: Node; - readonly startOffset: number; cloneContents(): DocumentFragment; cloneRange(): Range; collapse(toStart?: boolean): void; compareBoundaryPoints(how: number, sourceRange: Range): number; + /** + * Returns −1 if the point is before the range, 0 if the point is + * in the range, and 1 if the point is after the range. + */ + comparePoint(node: Node, offset: number): number; createContextualFragment(fragment: string): DocumentFragment; deleteContents(): void; detach(): void; - expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; getBoundingClientRect(): ClientRect | DOMRect; getClientRects(): ClientRectList | DOMRectList; insertNode(node: Node): void; + /** + * Returns whether range intersects node. + */ + intersectsNode(node: Node): boolean; isPointInRange(node: Node, offset: number): boolean; selectNode(node: Node): void; selectNodeContents(node: Node): void; @@ -11659,7 +11779,6 @@ interface Range { setStartAfter(node: Node): void; setStartBefore(node: Node): void; surroundContents(newParent: Node): void; - toString(): string; readonly END_TO_END: number; readonly END_TO_START: number; readonly START_TO_END: number; @@ -11934,8 +12053,8 @@ declare var SVGAnimatedPreserveAspectRatio: { }; interface SVGAnimatedRect { - readonly animVal: SVGRect; - readonly baseVal: SVGRect; + readonly animVal: DOMRectReadOnly; + readonly baseVal: DOMRect; } declare var SVGAnimatedRect: { @@ -11978,7 +12097,7 @@ declare var SVGCircleElement: { new(): SVGCircleElement; }; -interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { +interface SVGClipPathElement extends SVGGraphicsElement { readonly clipPathUnits: SVGAnimatedEnumeration; addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -12046,35 +12165,14 @@ declare var SVGDescElement: { new(): SVGDescElement; }; -interface SVGElementEventMap extends ElementEventMap { - "click": MouseEvent; - "dblclick": MouseEvent; - "focusin": FocusEvent; - "focusout": FocusEvent; - "load": Event; - "mousedown": MouseEvent; - "mousemove": MouseEvent; - "mouseout": MouseEvent; - "mouseover": MouseEvent; - "mouseup": MouseEvent; +interface SVGElementEventMap extends ElementEventMap, GlobalEventHandlersEventMap, DocumentAndElementEventHandlersEventMap { } -interface SVGElement extends Element, ElementCSSInlineStyle { +interface SVGElement extends Element, GlobalEventHandlers, DocumentAndElementEventHandlers, SVGElementInstance, HTMLOrSVGElement, ElementCSSInlineStyle { + /** @deprecated */ readonly className: any; - onclick: ((this: SVGElement, ev: MouseEvent) => any) | null; - ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null; - onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null; - onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null; - onload: ((this: SVGElement, ev: Event) => any) | null; - onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null; - onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null; - onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null; - onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null; - onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null; readonly ownerSVGElement: SVGSVGElement | null; readonly viewportElement: SVGElement | null; - /** @deprecated */ - xmlbase: string; addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -12087,14 +12185,8 @@ declare var SVGElement: { }; interface SVGElementInstance extends EventTarget { - readonly childNodes: SVGElementInstanceList; readonly correspondingElement: SVGElement; readonly correspondingUseElement: SVGUseElement; - readonly firstChild: SVGElementInstance; - readonly lastChild: SVGElementInstance; - readonly nextSibling: SVGElementInstance; - readonly parentNode: SVGElementInstance; - readonly previousSibling: SVGElementInstance; } declare var SVGElementInstance: { @@ -12587,7 +12679,7 @@ declare var SVGFETurbulenceElement: { readonly SVG_TURBULENCE_TYPE_UNKNOWN: number; }; -interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { +interface SVGFilterElement extends SVGElement, SVGURIReference { /** @deprecated */ readonly filterResX: SVGAnimatedInteger; /** @deprecated */ @@ -12652,7 +12744,24 @@ declare var SVGGElement: { new(): SVGGElement; }; -interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { +interface SVGGeometryElement extends SVGGraphicsElement { + readonly pathLength: SVGAnimatedNumber; + getPointAtLength(distance: number): DOMPoint; + getTotalLength(): number; + isPointInFill(point?: DOMPointInit): boolean; + isPointInStroke(point?: DOMPointInit): boolean; + addEventListener(type: K, listener: (this: SVGGeometryElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SVGGeometryElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SVGGeometryElement: { + prototype: SVGGeometryElement; + new(): SVGGeometryElement; +}; + +interface SVGGradientElement extends SVGElement, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; readonly gradientUnits: SVGAnimatedEnumeration; readonly spreadMethod: SVGAnimatedEnumeration; @@ -12676,16 +12785,10 @@ declare var SVGGradientElement: { }; interface SVGGraphicsElement extends SVGElement, SVGTests { - /** @deprecated */ - readonly farthestViewportElement: SVGElement | null; - /** @deprecated */ - readonly nearestViewportElement: SVGElement | null; readonly transform: SVGAnimatedTransformList; - getBBox(): SVGRect; - getCTM(): SVGMatrix | null; - getScreenCTM(): SVGMatrix | null; - /** @deprecated */ - getTransformToElement(element: SVGElement): SVGMatrix; + getBBox(options?: SVGBoundingBoxOptions): DOMRect; + getCTM(): DOMMatrix | null; + getScreenCTM(): DOMMatrix | null; addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -12751,6 +12854,7 @@ declare var SVGLength: { }; interface SVGLengthList { + readonly length: number; readonly numberOfItems: number; appendItem(newItem: SVGLength): SVGLength; clear(): void; @@ -12759,6 +12863,7 @@ interface SVGLengthList { insertItemBefore(newItem: SVGLength, index: number): SVGLength; removeItem(index: number): SVGLength; replaceItem(newItem: SVGLength, index: number): SVGLength; + [index: number]: SVGLength; } declare var SVGLengthList: { @@ -12831,7 +12936,7 @@ declare var SVGMarkerElement: { readonly SVG_MARKER_ORIENT_UNKNOWN: number; }; -interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { +interface SVGMaskElement extends SVGElement, SVGTests { readonly height: SVGAnimatedLength; readonly maskContentUnits: SVGAnimatedEnumeration; readonly maskUnits: SVGAnimatedEnumeration; @@ -12871,6 +12976,7 @@ declare var SVGNumber: { }; interface SVGNumberList { + readonly length: number; readonly numberOfItems: number; appendItem(newItem: SVGNumber): SVGNumber; clear(): void; @@ -12879,6 +12985,7 @@ interface SVGNumberList { insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; removeItem(index: number): SVGNumber; replaceItem(newItem: SVGNumber, index: number): SVGNumber; + [index: number]: SVGNumber; } declare var SVGNumberList: { @@ -13218,7 +13325,7 @@ declare var SVGPathSegMovetoRel: { new(): SVGPathSegMovetoRel; }; -interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { +interface SVGPatternElement extends SVGElement, SVGTests, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; readonly patternContentUnits: SVGAnimatedEnumeration; readonly patternTransform: SVGAnimatedTransformList; @@ -13351,10 +13458,6 @@ declare var SVGRectElement: { }; interface SVGSVGElementEventMap extends SVGElementEventMap { - "SVGAbort": Event; - "SVGError": Event; - "resize": UIEvent; - "scroll": UIEvent; "SVGUnload": Event; "SVGZoom": SVGZoomEvent; } @@ -13367,10 +13470,6 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB currentScale: number; readonly currentTranslate: SVGPoint; readonly height: SVGAnimatedLength; - onabort: ((this: SVGSVGElement, ev: Event) => any) | null; - onerror: ((this: SVGSVGElement, ev: Event) => any) | null; - onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null; - onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null; onunload: ((this: SVGSVGElement, ev: Event) => any) | null; onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; /** @deprecated */ @@ -13426,6 +13525,9 @@ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewB declare var SVGSVGElement: { prototype: SVGSVGElement; new(): SVGSVGElement; + readonly SVG_ZOOMANDPAN_DISABLE: number; + readonly SVG_ZOOMANDPAN_MAGNIFY: number; + readonly SVG_ZOOMANDPAN_UNKNOWN: number; }; interface SVGScriptElement extends SVGElement, SVGURIReference { @@ -13455,6 +13557,7 @@ declare var SVGStopElement: { }; interface SVGStringList { + readonly length: number; readonly numberOfItems: number; appendItem(newItem: string): string; clear(): void; @@ -13463,6 +13566,7 @@ interface SVGStringList { insertItemBefore(newItem: string, index: number): string; removeItem(index: number): string; replaceItem(newItem: string, index: number): string; + [index: number]: string; } declare var SVGStringList: { @@ -13524,11 +13628,7 @@ declare var SVGTSpanElement: { interface SVGTests { readonly requiredExtensions: SVGStringList; - /** @deprecated */ - readonly requiredFeatures: SVGStringList; readonly systemLanguage: SVGStringList; - /** @deprecated */ - hasExtension(extension: string): boolean; } interface SVGTextContentElement extends SVGGraphicsElement { @@ -13686,7 +13786,14 @@ interface SVGUnitTypes { readonly SVG_UNIT_TYPE_UNKNOWN: number; readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; } -declare var SVGUnitTypes: SVGUnitTypes; + +declare var SVGUnitTypes: { + prototype: SVGUnitTypes; + new(): SVGUnitTypes; + readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + readonly SVG_UNIT_TYPE_UNKNOWN: number; + readonly SVG_UNIT_TYPE_USERSPACEONUSE: number; +}; interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { readonly animatedInstanceRoot: SVGElementInstance | null; @@ -13718,6 +13825,9 @@ interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; + readonly SVG_ZOOMANDPAN_DISABLE: number; + readonly SVG_ZOOMANDPAN_MAGNIFY: number; + readonly SVG_ZOOMANDPAN_UNKNOWN: number; }; interface SVGZoomAndPan { @@ -13763,36 +13873,14 @@ declare var ScopedCredentialInfo: { new(): ScopedCredentialInfo; }; -interface ScreenEventMap { - "MSOrientationChange": Event; -} - -interface Screen extends EventTarget { +interface Screen { readonly availHeight: number; readonly availWidth: number; - /** @deprecated */ - bufferDepth: number; readonly colorDepth: number; - readonly deviceXDPI: number; - readonly deviceYDPI: number; - readonly fontSmoothingEnabled: boolean; readonly height: number; - readonly logicalXDPI: number; - readonly logicalYDPI: number; - readonly msOrientation: string; - onmsorientationchange: ((this: Screen, ev: Event) => any) | null; + readonly orientation: ScreenOrientation; readonly pixelDepth: number; - readonly systemXDPI: number; - readonly systemYDPI: number; readonly width: number; - lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean; - msLockOrientation(orientations: string | string[]): boolean; - msUnlockOrientation(): void; - unlockOrientation(): void; - addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Screen: { @@ -13800,6 +13888,27 @@ declare var Screen: { new(): Screen; }; +interface ScreenOrientationEventMap { + "change": Event; +} + +interface ScreenOrientation extends EventTarget { + readonly angle: number; + onchange: ((this: ScreenOrientation, ev: Event) => any) | null; + readonly type: OrientationType; + lock(orientation: OrientationLockType): Promise; + unlock(): void; + addEventListener(type: K, listener: (this: ScreenOrientation, ev: ScreenOrientationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: ScreenOrientation, ev: ScreenOrientationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var ScreenOrientation: { + prototype: ScreenOrientation; + new(): ScreenOrientation; +}; + interface ScriptProcessorNodeEventMap { "audioprocess": AudioProcessingEvent; } @@ -13886,7 +13995,7 @@ interface ServiceWorker extends EventTarget, AbstractWorker { onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; readonly scriptURL: string; readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; + postMessage(message: any, transfer?: Transferable[]): void; addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -13967,9 +14076,10 @@ declare var ServiceWorkerRegistration: { new(): ServiceWorkerRegistration; }; -interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { +interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment, DocumentOrShadowRoot { readonly host: Element; innerHTML: string; + readonly mode: ShadowRootMode; } interface ShadowRootInit { @@ -13977,6 +14087,10 @@ interface ShadowRootInit { mode: "open" | "closed"; } +interface Slotable { + readonly assignedSlot: HTMLSlotElement | null; +} + interface SourceBuffer extends EventTarget { appendWindowEnd: number; appendWindowStart: number; @@ -13993,20 +14107,144 @@ interface SourceBuffer extends EventTarget { remove(start: number, end: number): void; } -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +}; + +interface SourceBufferList extends EventTarget { + readonly length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +}; + +interface SpeechGrammar { + src: string; + weight: number; +} + +declare var SpeechGrammar: { + prototype: SpeechGrammar; + new(): SpeechGrammar; +}; + +interface SpeechGrammarList { + readonly length: number; + addFromString(string: string, weight?: number): void; + addFromURI(src: string, weight?: number): void; + item(index: number): SpeechGrammar; + [index: number]: SpeechGrammar; +} + +declare var SpeechGrammarList: { + prototype: SpeechGrammarList; + new(): SpeechGrammarList; +}; + +interface SpeechRecognitionEventMap { + "audioend": Event; + "audiostart": Event; + "end": Event; + "error": SpeechRecognitionError; + "nomatch": SpeechRecognitionEvent; + "result": SpeechRecognitionEvent; + "soundend": Event; + "soundstart": Event; + "speechend": Event; + "speechstart": Event; + "start": Event; +} + +interface SpeechRecognition extends EventTarget { + continuous: boolean; + grammars: SpeechGrammarList; + interimResults: boolean; + lang: string; + maxAlternatives: number; + onaudioend: ((this: SpeechRecognition, ev: Event) => any) | null; + onaudiostart: ((this: SpeechRecognition, ev: Event) => any) | null; + onend: ((this: SpeechRecognition, ev: Event) => any) | null; + onerror: ((this: SpeechRecognition, ev: SpeechRecognitionError) => any) | null; + onnomatch: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => any) | null; + onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => any) | null; + onsoundend: ((this: SpeechRecognition, ev: Event) => any) | null; + onsoundstart: ((this: SpeechRecognition, ev: Event) => any) | null; + onspeechend: ((this: SpeechRecognition, ev: Event) => any) | null; + onspeechstart: ((this: SpeechRecognition, ev: Event) => any) | null; + onstart: ((this: SpeechRecognition, ev: Event) => any) | null; + serviceURI: string; + abort(): void; + start(): void; + stop(): void; + addEventListener(type: K, listener: (this: SpeechRecognition, ev: SpeechRecognitionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: SpeechRecognition, ev: SpeechRecognitionEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var SpeechRecognition: { + prototype: SpeechRecognition; + new(): SpeechRecognition; +}; + +interface SpeechRecognitionAlternative { + readonly confidence: number; + readonly transcript: string; +} + +declare var SpeechRecognitionAlternative: { + prototype: SpeechRecognitionAlternative; + new(): SpeechRecognitionAlternative; +}; + +interface SpeechRecognitionError extends Event { + readonly error: SpeechRecognitionErrorCode; + readonly message: string; +} + +declare var SpeechRecognitionError: { + prototype: SpeechRecognitionError; + new(): SpeechRecognitionError; +}; + +interface SpeechRecognitionEvent extends Event { + readonly emma: Document | null; + readonly interpretation: any; + readonly resultIndex: number; + readonly results: SpeechRecognitionResultList; +} + +declare var SpeechRecognitionEvent: { + prototype: SpeechRecognitionEvent; + new(): SpeechRecognitionEvent; +}; + +interface SpeechRecognitionResult { + readonly isFinal: boolean; + readonly length: number; + item(index: number): SpeechRecognitionAlternative; + [index: number]: SpeechRecognitionAlternative; +} + +declare var SpeechRecognitionResult: { + prototype: SpeechRecognitionResult; + new(): SpeechRecognitionResult; }; -interface SourceBufferList extends EventTarget { +interface SpeechRecognitionResultList { readonly length: number; - item(index: number): SourceBuffer; - [index: number]: SourceBuffer; + item(index: number): SpeechRecognitionResult; + [index: number]: SpeechRecognitionResult; } -declare var SourceBufferList: { - prototype: SourceBufferList; - new(): SourceBufferList; +declare var SpeechRecognitionResultList: { + prototype: SpeechRecognitionResultList; + new(): SpeechRecognitionResultList; }; interface SpeechSynthesisEventMap { @@ -14034,9 +14272,17 @@ declare var SpeechSynthesis: { new(): SpeechSynthesis; }; +interface SpeechSynthesisErrorEvent extends SpeechSynthesisEvent { + readonly error: SpeechSynthesisErrorCode; +} + +declare var SpeechSynthesisErrorEvent: { + prototype: SpeechSynthesisErrorEvent; + new(): SpeechSynthesisErrorEvent; +}; + interface SpeechSynthesisEvent extends Event { readonly charIndex: number; - readonly charLength: number; readonly elapsedTime: number; readonly name: string; readonly utterance: SpeechSynthesisUtterance; @@ -14044,28 +14290,28 @@ interface SpeechSynthesisEvent extends Event { declare var SpeechSynthesisEvent: { prototype: SpeechSynthesisEvent; - new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent; + new(): SpeechSynthesisEvent; }; interface SpeechSynthesisUtteranceEventMap { - "boundary": Event; - "end": Event; - "error": Event; - "mark": Event; - "pause": Event; - "resume": Event; - "start": Event; + "boundary": SpeechSynthesisEvent; + "end": SpeechSynthesisEvent; + "error": SpeechSynthesisErrorEvent; + "mark": SpeechSynthesisEvent; + "pause": SpeechSynthesisEvent; + "resume": SpeechSynthesisEvent; + "start": SpeechSynthesisEvent; } interface SpeechSynthesisUtterance extends EventTarget { lang: string; - onboundary: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; - onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; - onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; - onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; - onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; - onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; - onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null; + onboundary: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onend: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onerror: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisErrorEvent) => any) | null; + onmark: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onpause: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onresume: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; + onstart: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null; pitch: number; rate: number; text: string; @@ -14096,6 +14342,14 @@ declare var SpeechSynthesisVoice: { new(): SpeechSynthesisVoice; }; +interface StaticRange extends AbstractRange { +} + +declare var StaticRange: { + prototype: StaticRange; + new(): StaticRange; +}; + interface StereoPannerNode extends AudioNode { readonly pan: AudioParam; } @@ -14132,6 +14386,7 @@ interface Storage { * storage[key] = value */ setItem(key: string, value: string): void; + [name: string]: any; } declare var Storage: { @@ -14250,9 +14505,15 @@ declare var SyncManager: { new(): SyncManager; }; -interface Text extends CharacterData { +interface Text extends CharacterData, Slotable { readonly assignedSlot: HTMLSlotElement | null; + /** + * Returns the combined data of all direct Text node siblings. + */ readonly wholeText: string; + /** + * Splits data at the given offset and returns the remainder as Text node. + */ splitText(offset: number): Text; } @@ -14343,6 +14604,20 @@ declare var TextEvent: { }; interface TextMetrics { + readonly actualBoundingBoxAscent: number; + readonly actualBoundingBoxDescent: number; + readonly actualBoundingBoxLeft: number; + readonly actualBoundingBoxRight: number; + readonly alphabeticBaseline: number; + readonly emHeightAscent: number; + readonly emHeightDescent: number; + readonly fontBoundingBoxAscent: number; + readonly fontBoundingBoxDescent: number; + readonly hangingBaseline: number; + /** + * Returns the measurement described below. + */ + readonly ideographicBaseline: number; readonly width: number; } @@ -14536,8 +14811,6 @@ declare var TransitionEvent: { interface TreeWalker { currentNode: Node; - /** @deprecated */ - readonly expandEntityReferences: boolean; readonly filter: NodeFilter | null; readonly root: Node; readonly whatToShow: number; @@ -14730,6 +15003,45 @@ declare var VRPose: { new(): VRPose; }; +interface VTTCue extends TextTrackCue { + align: AlignSetting; + line: LineAndPositionSetting; + lineAlign: LineAlignSetting; + position: LineAndPositionSetting; + positionAlign: PositionAlignSetting; + region: VTTRegion | null; + size: number; + snapToLines: boolean; + text: string; + vertical: DirectionSetting; + getCueAsHTML(): DocumentFragment; + addEventListener(type: K, listener: (this: VTTCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: VTTCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var VTTCue: { + prototype: VTTCue; + new(startTime: number, endTime: number, text: string): VTTCue; +}; + +interface VTTRegion { + id: string; + lines: number; + regionAnchorX: number; + regionAnchorY: number; + scroll: ScrollSetting; + viewportAnchorX: number; + viewportAnchorY: number; + width: number; +} + +declare var VTTRegion: { + prototype: VTTRegion; + new(): VTTRegion; +}; + interface ValidityState { readonly badInput: boolean; readonly customError: boolean; @@ -14967,8 +15279,8 @@ declare var WebAuthnAssertion: { interface WebGLActiveInfo { readonly name: string; - readonly size: number; - readonly type: number; + readonly size: GLint; + readonly type: GLenum; } declare var WebGLActiveInfo: { @@ -14990,7 +15302,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; - new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; + new(type: string, eventInit?: WebGLContextEventInit): WebGLContextEvent; }; interface WebGLFramebuffer extends WebGLObject { @@ -15025,71 +15337,376 @@ declare var WebGLRenderbuffer: { new(): WebGLRenderbuffer; }; -interface WebGLRenderingContext { +interface WebGLRenderingContext extends WebGLRenderingContextBase { +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; +}; + +interface WebGLRenderingContextBase { readonly canvas: HTMLCanvasElement; - readonly drawingBufferHeight: number; - readonly drawingBufferWidth: number; - activeTexture(texture: number): void; - attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; - bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void; - bindBuffer(target: number, buffer: WebGLBuffer | null): void; - bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void; - bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void; - bindTexture(target: number, texture: WebGLTexture | null): void; - blendColor(red: number, green: number, blue: number, alpha: number): void; - blendEquation(mode: number): void; - blendEquationSeparate(modeRGB: number, modeAlpha: number): void; - blendFunc(sfactor: number, dfactor: number): void; - blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; - bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void; - bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void; - checkFramebufferStatus(target: number): number; - clear(mask: number): void; - clearColor(red: number, green: number, blue: number, alpha: number): void; - clearDepth(depth: number): void; - clearStencil(s: number): void; - colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; - compileShader(shader: WebGLShader | null): void; - compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; - compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; - copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; - copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; + readonly drawingBufferHeight: GLsizei; + readonly drawingBufferWidth: GLsizei; + activeTexture(texture: GLenum): void; + attachShader(program: WebGLProgram, shader: WebGLShader): void; + bindAttribLocation(program: WebGLProgram, index: GLuint, name: string): void; + bindBuffer(target: GLenum, buffer: WebGLBuffer | null): void; + bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer | null): void; + bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + bindTexture(target: GLenum, texture: WebGLTexture | null): void; + blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + blendEquation(mode: GLenum): void; + blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum): void; + blendFunc(sfactor: GLenum, dfactor: GLenum): void; + blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum): void; + bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum): void; + bufferData(target: GLenum, data: BufferSource | null, usage: GLenum): void; + bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource): void; + checkFramebufferStatus(target: GLenum): GLenum; + clear(mask: GLbitfield): void; + clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf): void; + clearDepth(depth: GLclampf): void; + clearStencil(s: GLint): void; + colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean): void; + compileShader(shader: WebGLShader): void; + compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView): void; + compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView): void; + copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint): void; + copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; createBuffer(): WebGLBuffer | null; createFramebuffer(): WebGLFramebuffer | null; createProgram(): WebGLProgram | null; createRenderbuffer(): WebGLRenderbuffer | null; - createShader(type: number): WebGLShader | null; + createShader(type: GLenum): WebGLShader | null; createTexture(): WebGLTexture | null; - cullFace(mode: number): void; + cullFace(mode: GLenum): void; deleteBuffer(buffer: WebGLBuffer | null): void; deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void; deleteProgram(program: WebGLProgram | null): void; deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void; deleteShader(shader: WebGLShader | null): void; deleteTexture(texture: WebGLTexture | null): void; - depthFunc(func: number): void; - depthMask(flag: boolean): void; - depthRange(zNear: number, zFar: number): void; - detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void; - disable(cap: number): void; - disableVertexAttribArray(index: number): void; - drawArrays(mode: number, first: number, count: number): void; - drawElements(mode: number, count: number, type: number, offset: number): void; - enable(cap: number): void; - enableVertexAttribArray(index: number): void; + depthFunc(func: GLenum): void; + depthMask(flag: GLboolean): void; + depthRange(zNear: GLclampf, zFar: GLclampf): void; + detachShader(program: WebGLProgram, shader: WebGLShader): void; + disable(cap: GLenum): void; + disableVertexAttribArray(index: GLuint): void; + drawArrays(mode: GLenum, first: GLint, count: GLsizei): void; + drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr): void; + enable(cap: GLenum): void; + enableVertexAttribArray(index: GLuint): void; finish(): void; flush(): void; - framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void; - framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void; - frontFace(mode: number): void; - generateMipmap(target: number): void; - getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; - getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null; - getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null; - getAttribLocation(program: WebGLProgram | null, name: string): number; - getBufferParameter(target: number, pname: number): any; - getContextAttributes(): WebGLContextAttributes; - getError(): number; + framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer | null): void; + framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture | null, level: GLint): void; + frontFace(mode: GLenum): void; + generateMipmap(target: GLenum): void; + getActiveAttrib(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getActiveUniform(program: WebGLProgram, index: GLuint): WebGLActiveInfo | null; + getAttachedShaders(program: WebGLProgram): WebGLShader[] | null; + getAttribLocation(program: WebGLProgram, name: string): GLint; + getBufferParameter(target: GLenum, pname: GLenum): any; + getContextAttributes(): WebGLContextAttributes | null; + getError(): GLenum; getExtension(extensionName: "EXT_blend_minmax"): EXT_blend_minmax | null; getExtension(extensionName: "EXT_texture_filter_anisotropic"): EXT_texture_filter_anisotropic | null; getExtension(extensionName: "EXT_frag_depth"): EXT_frag_depth | null; @@ -15113,683 +15730,380 @@ interface WebGLRenderingContext { getExtension(extensionName: "OES_element_index_uint"): OES_element_index_uint | null; getExtension(extensionName: "ANGLE_instanced_arrays"): ANGLE_instanced_arrays | null; getExtension(extensionName: string): any; - getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; - getParameter(pname: number): any; - getProgramInfoLog(program: WebGLProgram | null): string | null; - getProgramParameter(program: WebGLProgram | null, pname: number): any; - getRenderbufferParameter(target: number, pname: number): any; - getShaderInfoLog(shader: WebGLShader | null): string | null; - getShaderParameter(shader: WebGLShader | null, pname: number): any; - getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null; - getShaderSource(shader: WebGLShader | null): string | null; + getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum): any; + getParameter(pname: GLenum): any; + getProgramInfoLog(program: WebGLProgram): string | null; + getProgramParameter(program: WebGLProgram, pname: GLenum): any; + getRenderbufferParameter(target: GLenum, pname: GLenum): any; + getShaderInfoLog(shader: WebGLShader): string | null; + getShaderParameter(shader: WebGLShader, pname: GLenum): any; + getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum): WebGLShaderPrecisionFormat | null; + getShaderSource(shader: WebGLShader): string | null; getSupportedExtensions(): string[] | null; - getTexParameter(target: number, pname: number): any; - getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any; - getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null; - getVertexAttrib(index: number, pname: number): any; - getVertexAttribOffset(index: number, pname: number): number; - hint(target: number, mode: number): void; - isBuffer(buffer: WebGLBuffer | null): boolean; + getTexParameter(target: GLenum, pname: GLenum): any; + getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; + getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation | null; + getVertexAttrib(index: GLuint, pname: GLenum): any; + getVertexAttribOffset(index: GLuint, pname: GLenum): GLintptr; + hint(target: GLenum, mode: GLenum): void; + isBuffer(buffer: WebGLBuffer | null): GLboolean; isContextLost(): boolean; - isEnabled(cap: number): boolean; - isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean; - isProgram(program: WebGLProgram | null): boolean; - isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean; - isShader(shader: WebGLShader | null): boolean; - isTexture(texture: WebGLTexture | null): boolean; - lineWidth(width: number): void; - linkProgram(program: WebGLProgram | null): void; - pixelStorei(pname: number, param: number | boolean): void; - polygonOffset(factor: number, units: number): void; - readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void; - renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; - sampleCoverage(value: number, invert: boolean): void; - scissor(x: number, y: number, width: number, height: number): void; - shaderSource(shader: WebGLShader | null, source: string): void; - stencilFunc(func: number, ref: number, mask: number): void; - stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; - stencilMask(mask: number): void; - stencilMaskSeparate(face: number, mask: number): void; - stencilOp(fail: number, zfail: number, zpass: number): void; - stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; - texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView | null): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; - texParameterf(target: number, pname: number, param: number): void; - texParameteri(target: number, pname: number, param: number): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; - uniform1f(location: WebGLUniformLocation | null, x: number): void; - uniform1fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void; - uniform1i(location: WebGLUniformLocation | null, x: number): void; - uniform1iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void; - uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void; - uniform2fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void; - uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void; - uniform2iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void; - uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; - uniform3fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void; - uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void; - uniform3iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void; - uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; - uniform4fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void; - uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void; - uniform4iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void; - uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: boolean, value: Float32Array | ArrayLike): void; - uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: boolean, value: Float32Array | ArrayLike): void; - uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: boolean, value: Float32Array | ArrayLike): void; + isEnabled(cap: GLenum): GLboolean; + isFramebuffer(framebuffer: WebGLFramebuffer | null): GLboolean; + isProgram(program: WebGLProgram | null): GLboolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): GLboolean; + isShader(shader: WebGLShader | null): GLboolean; + isTexture(texture: WebGLTexture | null): GLboolean; + lineWidth(width: GLfloat): void; + linkProgram(program: WebGLProgram): void; + pixelStorei(pname: GLenum, param: GLint): void; + polygonOffset(factor: GLfloat, units: GLfloat): void; + readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei): void; + sampleCoverage(value: GLclampf, invert: GLboolean): void; + scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + shaderSource(shader: WebGLShader, source: string): void; + stencilFunc(func: GLenum, ref: GLint, mask: GLuint): void; + stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint): void; + stencilMask(mask: GLuint): void; + stencilMaskSeparate(face: GLenum, mask: GLuint): void; + stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum): void; + stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + texParameterf(target: GLenum, pname: GLenum, param: GLfloat): void; + texParameteri(target: GLenum, pname: GLenum, param: GLint): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void; + texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource): void; + uniform1f(location: WebGLUniformLocation | null, x: GLfloat): void; + uniform1fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform1i(location: WebGLUniformLocation | null, x: GLint): void; + uniform1iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform2f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat): void; + uniform2fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform2i(location: WebGLUniformLocation | null, x: GLint, y: GLint): void; + uniform2iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform3f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat): void; + uniform3fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform3i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint): void; + uniform3iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniform4f(location: WebGLUniformLocation | null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + uniform4fv(location: WebGLUniformLocation | null, v: Float32List): void; + uniform4i(location: WebGLUniformLocation | null, x: GLint, y: GLint, z: GLint, w: GLint): void; + uniform4iv(location: WebGLUniformLocation | null, v: Int32List): void; + uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; + uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; useProgram(program: WebGLProgram | null): void; - validateProgram(program: WebGLProgram | null): void; - vertexAttrib1f(indx: number, x: number): void; - vertexAttrib1fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib2f(indx: number, x: number, y: number): void; - vertexAttrib2fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib3f(indx: number, x: number, y: number, z: number): void; - vertexAttrib3fv(indx: number, values: Float32Array | number[]): void; - vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; - vertexAttrib4fv(indx: number, values: Float32Array | number[]): void; - vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; - viewport(x: number, y: number, width: number, height: number): void; - readonly ACTIVE_ATTRIBUTES: number; - readonly ACTIVE_TEXTURE: number; - readonly ACTIVE_UNIFORMS: number; - readonly ALIASED_LINE_WIDTH_RANGE: number; - readonly ALIASED_POINT_SIZE_RANGE: number; - readonly ALPHA: number; - readonly ALPHA_BITS: number; - readonly ALWAYS: number; - readonly ARRAY_BUFFER: number; - readonly ARRAY_BUFFER_BINDING: number; - readonly ATTACHED_SHADERS: number; - readonly BACK: number; - readonly BLEND: number; - readonly BLEND_COLOR: number; - readonly BLEND_DST_ALPHA: number; - readonly BLEND_DST_RGB: number; - readonly BLEND_EQUATION: number; - readonly BLEND_EQUATION_ALPHA: number; - readonly BLEND_EQUATION_RGB: number; - readonly BLEND_SRC_ALPHA: number; - readonly BLEND_SRC_RGB: number; - readonly BLUE_BITS: number; - readonly BOOL: number; - readonly BOOL_VEC2: number; - readonly BOOL_VEC3: number; - readonly BOOL_VEC4: number; - readonly BROWSER_DEFAULT_WEBGL: number; - readonly BUFFER_SIZE: number; - readonly BUFFER_USAGE: number; - readonly BYTE: number; - readonly CCW: number; - readonly CLAMP_TO_EDGE: number; - readonly COLOR_ATTACHMENT0: number; - readonly COLOR_BUFFER_BIT: number; - readonly COLOR_CLEAR_VALUE: number; - readonly COLOR_WRITEMASK: number; - readonly COMPILE_STATUS: number; - readonly COMPRESSED_TEXTURE_FORMATS: number; - readonly CONSTANT_ALPHA: number; - readonly CONSTANT_COLOR: number; - readonly CONTEXT_LOST_WEBGL: number; - readonly CULL_FACE: number; - readonly CULL_FACE_MODE: number; - readonly CURRENT_PROGRAM: number; - readonly CURRENT_VERTEX_ATTRIB: number; - readonly CW: number; - readonly DECR: number; - readonly DECR_WRAP: number; - readonly DELETE_STATUS: number; - readonly DEPTH_ATTACHMENT: number; - readonly DEPTH_BITS: number; - readonly DEPTH_BUFFER_BIT: number; - readonly DEPTH_CLEAR_VALUE: number; - readonly DEPTH_COMPONENT: number; - readonly DEPTH_COMPONENT16: number; - readonly DEPTH_FUNC: number; - readonly DEPTH_RANGE: number; - readonly DEPTH_STENCIL: number; - readonly DEPTH_STENCIL_ATTACHMENT: number; - readonly DEPTH_TEST: number; - readonly DEPTH_WRITEMASK: number; - readonly DITHER: number; - readonly DONT_CARE: number; - readonly DST_ALPHA: number; - readonly DST_COLOR: number; - readonly DYNAMIC_DRAW: number; - readonly ELEMENT_ARRAY_BUFFER: number; - readonly ELEMENT_ARRAY_BUFFER_BINDING: number; - readonly EQUAL: number; - readonly FASTEST: number; - readonly FLOAT: number; - readonly FLOAT_MAT2: number; - readonly FLOAT_MAT3: number; - readonly FLOAT_MAT4: number; - readonly FLOAT_VEC2: number; - readonly FLOAT_VEC3: number; - readonly FLOAT_VEC4: number; - readonly FRAGMENT_SHADER: number; - readonly FRAMEBUFFER: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; - readonly FRAMEBUFFER_BINDING: number; - readonly FRAMEBUFFER_COMPLETE: number; - readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; - readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; - readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; - readonly FRAMEBUFFER_UNSUPPORTED: number; - readonly FRONT: number; - readonly FRONT_AND_BACK: number; - readonly FRONT_FACE: number; - readonly FUNC_ADD: number; - readonly FUNC_REVERSE_SUBTRACT: number; - readonly FUNC_SUBTRACT: number; - readonly GENERATE_MIPMAP_HINT: number; - readonly GEQUAL: number; - readonly GREATER: number; - readonly GREEN_BITS: number; - readonly HIGH_FLOAT: number; - readonly HIGH_INT: number; - readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; - readonly IMPLEMENTATION_COLOR_READ_TYPE: number; - readonly INCR: number; - readonly INCR_WRAP: number; - readonly INT: number; - readonly INT_VEC2: number; - readonly INT_VEC3: number; - readonly INT_VEC4: number; - readonly INVALID_ENUM: number; - readonly INVALID_FRAMEBUFFER_OPERATION: number; - readonly INVALID_OPERATION: number; - readonly INVALID_VALUE: number; - readonly INVERT: number; - readonly KEEP: number; - readonly LEQUAL: number; - readonly LESS: number; - readonly LINEAR: number; - readonly LINEAR_MIPMAP_LINEAR: number; - readonly LINEAR_MIPMAP_NEAREST: number; - readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; - readonly LINK_STATUS: number; - readonly LOW_FLOAT: number; - readonly LOW_INT: number; - readonly LUMINANCE: number; - readonly LUMINANCE_ALPHA: number; - readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; - readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; - readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; - readonly MAX_RENDERBUFFER_SIZE: number; - readonly MAX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_TEXTURE_SIZE: number; - readonly MAX_VARYING_VECTORS: number; - readonly MAX_VERTEX_ATTRIBS: number; - readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_VERTEX_UNIFORM_VECTORS: number; - readonly MAX_VIEWPORT_DIMS: number; - readonly MEDIUM_FLOAT: number; - readonly MEDIUM_INT: number; - readonly MIRRORED_REPEAT: number; - readonly NEAREST: number; - readonly NEAREST_MIPMAP_LINEAR: number; - readonly NEAREST_MIPMAP_NEAREST: number; - readonly NEVER: number; - readonly NICEST: number; - readonly NONE: number; - readonly NOTEQUAL: number; - readonly NO_ERROR: number; - readonly ONE: number; - readonly ONE_MINUS_CONSTANT_ALPHA: number; - readonly ONE_MINUS_CONSTANT_COLOR: number; - readonly ONE_MINUS_DST_ALPHA: number; - readonly ONE_MINUS_DST_COLOR: number; - readonly ONE_MINUS_SRC_ALPHA: number; - readonly ONE_MINUS_SRC_COLOR: number; - readonly OUT_OF_MEMORY: number; - readonly PACK_ALIGNMENT: number; - readonly POINTS: number; - readonly POLYGON_OFFSET_FACTOR: number; - readonly POLYGON_OFFSET_FILL: number; - readonly POLYGON_OFFSET_UNITS: number; - readonly RED_BITS: number; - readonly RENDERBUFFER: number; - readonly RENDERBUFFER_ALPHA_SIZE: number; - readonly RENDERBUFFER_BINDING: number; - readonly RENDERBUFFER_BLUE_SIZE: number; - readonly RENDERBUFFER_DEPTH_SIZE: number; - readonly RENDERBUFFER_GREEN_SIZE: number; - readonly RENDERBUFFER_HEIGHT: number; - readonly RENDERBUFFER_INTERNAL_FORMAT: number; - readonly RENDERBUFFER_RED_SIZE: number; - readonly RENDERBUFFER_STENCIL_SIZE: number; - readonly RENDERBUFFER_WIDTH: number; - readonly RENDERER: number; - readonly REPEAT: number; - readonly REPLACE: number; - readonly RGB: number; - readonly RGB565: number; - readonly RGB5_A1: number; - readonly RGBA: number; - readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; - readonly SAMPLE_ALPHA_TO_COVERAGE: number; - readonly SAMPLE_BUFFERS: number; - readonly SAMPLE_COVERAGE: number; - readonly SAMPLE_COVERAGE_INVERT: number; - readonly SAMPLE_COVERAGE_VALUE: number; - readonly SCISSOR_BOX: number; - readonly SCISSOR_TEST: number; - readonly SHADER_TYPE: number; - readonly SHADING_LANGUAGE_VERSION: number; - readonly SHORT: number; - readonly SRC_ALPHA: number; - readonly SRC_ALPHA_SATURATE: number; - readonly SRC_COLOR: number; - readonly STATIC_DRAW: number; - readonly STENCIL_ATTACHMENT: number; - readonly STENCIL_BACK_FAIL: number; - readonly STENCIL_BACK_FUNC: number; - readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; - readonly STENCIL_BACK_PASS_DEPTH_PASS: number; - readonly STENCIL_BACK_REF: number; - readonly STENCIL_BACK_VALUE_MASK: number; - readonly STENCIL_BACK_WRITEMASK: number; - readonly STENCIL_BITS: number; - readonly STENCIL_BUFFER_BIT: number; - readonly STENCIL_CLEAR_VALUE: number; - readonly STENCIL_FAIL: number; - readonly STENCIL_FUNC: number; - readonly STENCIL_INDEX: number; - readonly STENCIL_INDEX8: number; - readonly STENCIL_PASS_DEPTH_FAIL: number; - readonly STENCIL_PASS_DEPTH_PASS: number; - readonly STENCIL_REF: number; - readonly STENCIL_TEST: number; - readonly STENCIL_VALUE_MASK: number; - readonly STENCIL_WRITEMASK: number; - readonly STREAM_DRAW: number; - readonly SUBPIXEL_BITS: number; - readonly TEXTURE: number; - readonly TEXTURE0: number; - readonly TEXTURE1: number; - readonly TEXTURE10: number; - readonly TEXTURE11: number; - readonly TEXTURE12: number; - readonly TEXTURE13: number; - readonly TEXTURE14: number; - readonly TEXTURE15: number; - readonly TEXTURE16: number; - readonly TEXTURE17: number; - readonly TEXTURE18: number; - readonly TEXTURE19: number; - readonly TEXTURE2: number; - readonly TEXTURE20: number; - readonly TEXTURE21: number; - readonly TEXTURE22: number; - readonly TEXTURE23: number; - readonly TEXTURE24: number; - readonly TEXTURE25: number; - readonly TEXTURE26: number; - readonly TEXTURE27: number; - readonly TEXTURE28: number; - readonly TEXTURE29: number; - readonly TEXTURE3: number; - readonly TEXTURE30: number; - readonly TEXTURE31: number; - readonly TEXTURE4: number; - readonly TEXTURE5: number; - readonly TEXTURE6: number; - readonly TEXTURE7: number; - readonly TEXTURE8: number; - readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; - readonly TRIANGLE_FAN: number; - readonly TRIANGLE_STRIP: number; - readonly UNPACK_ALIGNMENT: number; - readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; - readonly UNPACK_FLIP_Y_WEBGL: number; - readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; - readonly UNSIGNED_BYTE: number; - readonly UNSIGNED_INT: number; - readonly UNSIGNED_SHORT: number; - readonly UNSIGNED_SHORT_4_4_4_4: number; - readonly UNSIGNED_SHORT_5_5_5_1: number; - readonly UNSIGNED_SHORT_5_6_5: number; - readonly VALIDATE_STATUS: number; - readonly VENDOR: number; - readonly VERSION: number; - readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; - readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; - readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; - readonly VERTEX_ATTRIB_ARRAY_POINTER: number; - readonly VERTEX_ATTRIB_ARRAY_SIZE: number; - readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; - readonly VERTEX_ATTRIB_ARRAY_TYPE: number; - readonly VERTEX_SHADER: number; - readonly VIEWPORT: number; - readonly ZERO: number; + validateProgram(program: WebGLProgram): void; + vertexAttrib1f(index: GLuint, x: GLfloat): void; + vertexAttrib1fv(index: GLuint, values: Float32List): void; + vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat): void; + vertexAttrib2fv(index: GLuint, values: Float32List): void; + vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat): void; + vertexAttrib3fv(index: GLuint, values: Float32List): void; + vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat): void; + vertexAttrib4fv(index: GLuint, values: Float32List): void; + vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr): void; + viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; + readonly ACTIVE_ATTRIBUTES: GLenum; + readonly ACTIVE_TEXTURE: GLenum; + readonly ACTIVE_UNIFORMS: GLenum; + readonly ALIASED_LINE_WIDTH_RANGE: GLenum; + readonly ALIASED_POINT_SIZE_RANGE: GLenum; + readonly ALPHA: GLenum; + readonly ALPHA_BITS: GLenum; + readonly ALWAYS: GLenum; + readonly ARRAY_BUFFER: GLenum; + readonly ARRAY_BUFFER_BINDING: GLenum; + readonly ATTACHED_SHADERS: GLenum; + readonly BACK: GLenum; + readonly BLEND: GLenum; + readonly BLEND_COLOR: GLenum; + readonly BLEND_DST_ALPHA: GLenum; + readonly BLEND_DST_RGB: GLenum; + readonly BLEND_EQUATION: GLenum; + readonly BLEND_EQUATION_ALPHA: GLenum; + readonly BLEND_EQUATION_RGB: GLenum; + readonly BLEND_SRC_ALPHA: GLenum; + readonly BLEND_SRC_RGB: GLenum; + readonly BLUE_BITS: GLenum; + readonly BOOL: GLenum; + readonly BOOL_VEC2: GLenum; + readonly BOOL_VEC3: GLenum; + readonly BOOL_VEC4: GLenum; + readonly BROWSER_DEFAULT_WEBGL: GLenum; + readonly BUFFER_SIZE: GLenum; + readonly BUFFER_USAGE: GLenum; + readonly BYTE: GLenum; + readonly CCW: GLenum; + readonly CLAMP_TO_EDGE: GLenum; + readonly COLOR_ATTACHMENT0: GLenum; + readonly COLOR_BUFFER_BIT: GLenum; + readonly COLOR_CLEAR_VALUE: GLenum; + readonly COLOR_WRITEMASK: GLenum; + readonly COMPILE_STATUS: GLenum; + readonly COMPRESSED_TEXTURE_FORMATS: GLenum; + readonly CONSTANT_ALPHA: GLenum; + readonly CONSTANT_COLOR: GLenum; + readonly CONTEXT_LOST_WEBGL: GLenum; + readonly CULL_FACE: GLenum; + readonly CULL_FACE_MODE: GLenum; + readonly CURRENT_PROGRAM: GLenum; + readonly CURRENT_VERTEX_ATTRIB: GLenum; + readonly CW: GLenum; + readonly DECR: GLenum; + readonly DECR_WRAP: GLenum; + readonly DELETE_STATUS: GLenum; + readonly DEPTH_ATTACHMENT: GLenum; + readonly DEPTH_BITS: GLenum; + readonly DEPTH_BUFFER_BIT: GLenum; + readonly DEPTH_CLEAR_VALUE: GLenum; + readonly DEPTH_COMPONENT: GLenum; + readonly DEPTH_COMPONENT16: GLenum; + readonly DEPTH_FUNC: GLenum; + readonly DEPTH_RANGE: GLenum; + readonly DEPTH_STENCIL: GLenum; + readonly DEPTH_STENCIL_ATTACHMENT: GLenum; + readonly DEPTH_TEST: GLenum; + readonly DEPTH_WRITEMASK: GLenum; + readonly DITHER: GLenum; + readonly DONT_CARE: GLenum; + readonly DST_ALPHA: GLenum; + readonly DST_COLOR: GLenum; + readonly DYNAMIC_DRAW: GLenum; + readonly ELEMENT_ARRAY_BUFFER: GLenum; + readonly ELEMENT_ARRAY_BUFFER_BINDING: GLenum; + readonly EQUAL: GLenum; + readonly FASTEST: GLenum; + readonly FLOAT: GLenum; + readonly FLOAT_MAT2: GLenum; + readonly FLOAT_MAT3: GLenum; + readonly FLOAT_MAT4: GLenum; + readonly FLOAT_VEC2: GLenum; + readonly FLOAT_VEC3: GLenum; + readonly FLOAT_VEC4: GLenum; + readonly FRAGMENT_SHADER: GLenum; + readonly FRAMEBUFFER: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; + readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; + readonly FRAMEBUFFER_BINDING: GLenum; + readonly FRAMEBUFFER_COMPLETE: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; + readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; + readonly FRAMEBUFFER_UNSUPPORTED: GLenum; + readonly FRONT: GLenum; + readonly FRONT_AND_BACK: GLenum; + readonly FRONT_FACE: GLenum; + readonly FUNC_ADD: GLenum; + readonly FUNC_REVERSE_SUBTRACT: GLenum; + readonly FUNC_SUBTRACT: GLenum; + readonly GENERATE_MIPMAP_HINT: GLenum; + readonly GEQUAL: GLenum; + readonly GREATER: GLenum; + readonly GREEN_BITS: GLenum; + readonly HIGH_FLOAT: GLenum; + readonly HIGH_INT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; + readonly IMPLEMENTATION_COLOR_READ_TYPE: GLenum; + readonly INCR: GLenum; + readonly INCR_WRAP: GLenum; + readonly INT: GLenum; + readonly INT_VEC2: GLenum; + readonly INT_VEC3: GLenum; + readonly INT_VEC4: GLenum; + readonly INVALID_ENUM: GLenum; + readonly INVALID_FRAMEBUFFER_OPERATION: GLenum; + readonly INVALID_OPERATION: GLenum; + readonly INVALID_VALUE: GLenum; + readonly INVERT: GLenum; + readonly KEEP: GLenum; + readonly LEQUAL: GLenum; + readonly LESS: GLenum; + readonly LINEAR: GLenum; + readonly LINEAR_MIPMAP_LINEAR: GLenum; + readonly LINEAR_MIPMAP_NEAREST: GLenum; + readonly LINES: GLenum; + readonly LINE_LOOP: GLenum; + readonly LINE_STRIP: GLenum; + readonly LINE_WIDTH: GLenum; + readonly LINK_STATUS: GLenum; + readonly LOW_FLOAT: GLenum; + readonly LOW_INT: GLenum; + readonly LUMINANCE: GLenum; + readonly LUMINANCE_ALPHA: GLenum; + readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; + readonly MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; + readonly MAX_RENDERBUFFER_SIZE: GLenum; + readonly MAX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_TEXTURE_SIZE: GLenum; + readonly MAX_VARYING_VECTORS: GLenum; + readonly MAX_VERTEX_ATTRIBS: GLenum; + readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; + readonly MAX_VERTEX_UNIFORM_VECTORS: GLenum; + readonly MAX_VIEWPORT_DIMS: GLenum; + readonly MEDIUM_FLOAT: GLenum; + readonly MEDIUM_INT: GLenum; + readonly MIRRORED_REPEAT: GLenum; + readonly NEAREST: GLenum; + readonly NEAREST_MIPMAP_LINEAR: GLenum; + readonly NEAREST_MIPMAP_NEAREST: GLenum; + readonly NEVER: GLenum; + readonly NICEST: GLenum; + readonly NONE: GLenum; + readonly NOTEQUAL: GLenum; + readonly NO_ERROR: GLenum; + readonly ONE: GLenum; + readonly ONE_MINUS_CONSTANT_ALPHA: GLenum; + readonly ONE_MINUS_CONSTANT_COLOR: GLenum; + readonly ONE_MINUS_DST_ALPHA: GLenum; + readonly ONE_MINUS_DST_COLOR: GLenum; + readonly ONE_MINUS_SRC_ALPHA: GLenum; + readonly ONE_MINUS_SRC_COLOR: GLenum; + readonly OUT_OF_MEMORY: GLenum; + readonly PACK_ALIGNMENT: GLenum; + readonly POINTS: GLenum; + readonly POLYGON_OFFSET_FACTOR: GLenum; + readonly POLYGON_OFFSET_FILL: GLenum; + readonly POLYGON_OFFSET_UNITS: GLenum; + readonly RED_BITS: GLenum; + readonly RENDERBUFFER: GLenum; + readonly RENDERBUFFER_ALPHA_SIZE: GLenum; + readonly RENDERBUFFER_BINDING: GLenum; + readonly RENDERBUFFER_BLUE_SIZE: GLenum; + readonly RENDERBUFFER_DEPTH_SIZE: GLenum; + readonly RENDERBUFFER_GREEN_SIZE: GLenum; + readonly RENDERBUFFER_HEIGHT: GLenum; + readonly RENDERBUFFER_INTERNAL_FORMAT: GLenum; + readonly RENDERBUFFER_RED_SIZE: GLenum; + readonly RENDERBUFFER_STENCIL_SIZE: GLenum; + readonly RENDERBUFFER_WIDTH: GLenum; + readonly RENDERER: GLenum; + readonly REPEAT: GLenum; + readonly REPLACE: GLenum; + readonly RGB: GLenum; + readonly RGB565: GLenum; + readonly RGB5_A1: GLenum; + readonly RGBA: GLenum; + readonly RGBA4: GLenum; + readonly SAMPLER_2D: GLenum; + readonly SAMPLER_CUBE: GLenum; + readonly SAMPLES: GLenum; + readonly SAMPLE_ALPHA_TO_COVERAGE: GLenum; + readonly SAMPLE_BUFFERS: GLenum; + readonly SAMPLE_COVERAGE: GLenum; + readonly SAMPLE_COVERAGE_INVERT: GLenum; + readonly SAMPLE_COVERAGE_VALUE: GLenum; + readonly SCISSOR_BOX: GLenum; + readonly SCISSOR_TEST: GLenum; + readonly SHADER_TYPE: GLenum; + readonly SHADING_LANGUAGE_VERSION: GLenum; + readonly SHORT: GLenum; + readonly SRC_ALPHA: GLenum; + readonly SRC_ALPHA_SATURATE: GLenum; + readonly SRC_COLOR: GLenum; + readonly STATIC_DRAW: GLenum; + readonly STENCIL_ATTACHMENT: GLenum; + readonly STENCIL_BACK_FAIL: GLenum; + readonly STENCIL_BACK_FUNC: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_BACK_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_BACK_REF: GLenum; + readonly STENCIL_BACK_VALUE_MASK: GLenum; + readonly STENCIL_BACK_WRITEMASK: GLenum; + readonly STENCIL_BITS: GLenum; + readonly STENCIL_BUFFER_BIT: GLenum; + readonly STENCIL_CLEAR_VALUE: GLenum; + readonly STENCIL_FAIL: GLenum; + readonly STENCIL_FUNC: GLenum; + readonly STENCIL_INDEX8: GLenum; + readonly STENCIL_PASS_DEPTH_FAIL: GLenum; + readonly STENCIL_PASS_DEPTH_PASS: GLenum; + readonly STENCIL_REF: GLenum; + readonly STENCIL_TEST: GLenum; + readonly STENCIL_VALUE_MASK: GLenum; + readonly STENCIL_WRITEMASK: GLenum; + readonly STREAM_DRAW: GLenum; + readonly SUBPIXEL_BITS: GLenum; + readonly TEXTURE: GLenum; + readonly TEXTURE0: GLenum; + readonly TEXTURE1: GLenum; + readonly TEXTURE10: GLenum; + readonly TEXTURE11: GLenum; + readonly TEXTURE12: GLenum; + readonly TEXTURE13: GLenum; + readonly TEXTURE14: GLenum; + readonly TEXTURE15: GLenum; + readonly TEXTURE16: GLenum; + readonly TEXTURE17: GLenum; + readonly TEXTURE18: GLenum; + readonly TEXTURE19: GLenum; + readonly TEXTURE2: GLenum; + readonly TEXTURE20: GLenum; + readonly TEXTURE21: GLenum; + readonly TEXTURE22: GLenum; + readonly TEXTURE23: GLenum; + readonly TEXTURE24: GLenum; + readonly TEXTURE25: GLenum; + readonly TEXTURE26: GLenum; + readonly TEXTURE27: GLenum; + readonly TEXTURE28: GLenum; + readonly TEXTURE29: GLenum; + readonly TEXTURE3: GLenum; + readonly TEXTURE30: GLenum; + readonly TEXTURE31: GLenum; + readonly TEXTURE4: GLenum; + readonly TEXTURE5: GLenum; + readonly TEXTURE6: GLenum; + readonly TEXTURE7: GLenum; + readonly TEXTURE8: GLenum; + readonly TEXTURE9: GLenum; + readonly TEXTURE_2D: GLenum; + readonly TEXTURE_BINDING_2D: GLenum; + readonly TEXTURE_BINDING_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; + readonly TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; + readonly TEXTURE_MAG_FILTER: GLenum; + readonly TEXTURE_MIN_FILTER: GLenum; + readonly TEXTURE_WRAP_S: GLenum; + readonly TEXTURE_WRAP_T: GLenum; + readonly TRIANGLES: GLenum; + readonly TRIANGLE_FAN: GLenum; + readonly TRIANGLE_STRIP: GLenum; + readonly UNPACK_ALIGNMENT: GLenum; + readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; + readonly UNPACK_FLIP_Y_WEBGL: GLenum; + readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; + readonly UNSIGNED_BYTE: GLenum; + readonly UNSIGNED_INT: GLenum; + readonly UNSIGNED_SHORT: GLenum; + readonly UNSIGNED_SHORT_4_4_4_4: GLenum; + readonly UNSIGNED_SHORT_5_5_5_1: GLenum; + readonly UNSIGNED_SHORT_5_6_5: GLenum; + readonly VALIDATE_STATUS: GLenum; + readonly VENDOR: GLenum; + readonly VERSION: GLenum; + readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; + readonly VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; + readonly VERTEX_ATTRIB_ARRAY_POINTER: GLenum; + readonly VERTEX_ATTRIB_ARRAY_SIZE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; + readonly VERTEX_ATTRIB_ARRAY_TYPE: GLenum; + readonly VERTEX_SHADER: GLenum; + readonly VIEWPORT: GLenum; + readonly ZERO: GLenum; } -declare var WebGLRenderingContext: { - prototype: WebGLRenderingContext; - new(): WebGLRenderingContext; - readonly ACTIVE_ATTRIBUTES: number; - readonly ACTIVE_TEXTURE: number; - readonly ACTIVE_UNIFORMS: number; - readonly ALIASED_LINE_WIDTH_RANGE: number; - readonly ALIASED_POINT_SIZE_RANGE: number; - readonly ALPHA: number; - readonly ALPHA_BITS: number; - readonly ALWAYS: number; - readonly ARRAY_BUFFER: number; - readonly ARRAY_BUFFER_BINDING: number; - readonly ATTACHED_SHADERS: number; - readonly BACK: number; - readonly BLEND: number; - readonly BLEND_COLOR: number; - readonly BLEND_DST_ALPHA: number; - readonly BLEND_DST_RGB: number; - readonly BLEND_EQUATION: number; - readonly BLEND_EQUATION_ALPHA: number; - readonly BLEND_EQUATION_RGB: number; - readonly BLEND_SRC_ALPHA: number; - readonly BLEND_SRC_RGB: number; - readonly BLUE_BITS: number; - readonly BOOL: number; - readonly BOOL_VEC2: number; - readonly BOOL_VEC3: number; - readonly BOOL_VEC4: number; - readonly BROWSER_DEFAULT_WEBGL: number; - readonly BUFFER_SIZE: number; - readonly BUFFER_USAGE: number; - readonly BYTE: number; - readonly CCW: number; - readonly CLAMP_TO_EDGE: number; - readonly COLOR_ATTACHMENT0: number; - readonly COLOR_BUFFER_BIT: number; - readonly COLOR_CLEAR_VALUE: number; - readonly COLOR_WRITEMASK: number; - readonly COMPILE_STATUS: number; - readonly COMPRESSED_TEXTURE_FORMATS: number; - readonly CONSTANT_ALPHA: number; - readonly CONSTANT_COLOR: number; - readonly CONTEXT_LOST_WEBGL: number; - readonly CULL_FACE: number; - readonly CULL_FACE_MODE: number; - readonly CURRENT_PROGRAM: number; - readonly CURRENT_VERTEX_ATTRIB: number; - readonly CW: number; - readonly DECR: number; - readonly DECR_WRAP: number; - readonly DELETE_STATUS: number; - readonly DEPTH_ATTACHMENT: number; - readonly DEPTH_BITS: number; - readonly DEPTH_BUFFER_BIT: number; - readonly DEPTH_CLEAR_VALUE: number; - readonly DEPTH_COMPONENT: number; - readonly DEPTH_COMPONENT16: number; - readonly DEPTH_FUNC: number; - readonly DEPTH_RANGE: number; - readonly DEPTH_STENCIL: number; - readonly DEPTH_STENCIL_ATTACHMENT: number; - readonly DEPTH_TEST: number; - readonly DEPTH_WRITEMASK: number; - readonly DITHER: number; - readonly DONT_CARE: number; - readonly DST_ALPHA: number; - readonly DST_COLOR: number; - readonly DYNAMIC_DRAW: number; - readonly ELEMENT_ARRAY_BUFFER: number; - readonly ELEMENT_ARRAY_BUFFER_BINDING: number; - readonly EQUAL: number; - readonly FASTEST: number; - readonly FLOAT: number; - readonly FLOAT_MAT2: number; - readonly FLOAT_MAT3: number; - readonly FLOAT_MAT4: number; - readonly FLOAT_VEC2: number; - readonly FLOAT_VEC3: number; - readonly FLOAT_VEC4: number; - readonly FRAGMENT_SHADER: number; - readonly FRAMEBUFFER: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; - readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; - readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; - readonly FRAMEBUFFER_BINDING: number; - readonly FRAMEBUFFER_COMPLETE: number; - readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; - readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; - readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; - readonly FRAMEBUFFER_UNSUPPORTED: number; - readonly FRONT: number; - readonly FRONT_AND_BACK: number; - readonly FRONT_FACE: number; - readonly FUNC_ADD: number; - readonly FUNC_REVERSE_SUBTRACT: number; - readonly FUNC_SUBTRACT: number; - readonly GENERATE_MIPMAP_HINT: number; - readonly GEQUAL: number; - readonly GREATER: number; - readonly GREEN_BITS: number; - readonly HIGH_FLOAT: number; - readonly HIGH_INT: number; - readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; - readonly IMPLEMENTATION_COLOR_READ_TYPE: number; - readonly INCR: number; - readonly INCR_WRAP: number; - readonly INT: number; - readonly INT_VEC2: number; - readonly INT_VEC3: number; - readonly INT_VEC4: number; - readonly INVALID_ENUM: number; - readonly INVALID_FRAMEBUFFER_OPERATION: number; - readonly INVALID_OPERATION: number; - readonly INVALID_VALUE: number; - readonly INVERT: number; - readonly KEEP: number; - readonly LEQUAL: number; - readonly LESS: number; - readonly LINEAR: number; - readonly LINEAR_MIPMAP_LINEAR: number; - readonly LINEAR_MIPMAP_NEAREST: number; - readonly LINES: number; - readonly LINE_LOOP: number; - readonly LINE_STRIP: number; - readonly LINE_WIDTH: number; - readonly LINK_STATUS: number; - readonly LOW_FLOAT: number; - readonly LOW_INT: number; - readonly LUMINANCE: number; - readonly LUMINANCE_ALPHA: number; - readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; - readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; - readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; - readonly MAX_RENDERBUFFER_SIZE: number; - readonly MAX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_TEXTURE_SIZE: number; - readonly MAX_VARYING_VECTORS: number; - readonly MAX_VERTEX_ATTRIBS: number; - readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; - readonly MAX_VERTEX_UNIFORM_VECTORS: number; - readonly MAX_VIEWPORT_DIMS: number; - readonly MEDIUM_FLOAT: number; - readonly MEDIUM_INT: number; - readonly MIRRORED_REPEAT: number; - readonly NEAREST: number; - readonly NEAREST_MIPMAP_LINEAR: number; - readonly NEAREST_MIPMAP_NEAREST: number; - readonly NEVER: number; - readonly NICEST: number; - readonly NONE: number; - readonly NOTEQUAL: number; - readonly NO_ERROR: number; - readonly ONE: number; - readonly ONE_MINUS_CONSTANT_ALPHA: number; - readonly ONE_MINUS_CONSTANT_COLOR: number; - readonly ONE_MINUS_DST_ALPHA: number; - readonly ONE_MINUS_DST_COLOR: number; - readonly ONE_MINUS_SRC_ALPHA: number; - readonly ONE_MINUS_SRC_COLOR: number; - readonly OUT_OF_MEMORY: number; - readonly PACK_ALIGNMENT: number; - readonly POINTS: number; - readonly POLYGON_OFFSET_FACTOR: number; - readonly POLYGON_OFFSET_FILL: number; - readonly POLYGON_OFFSET_UNITS: number; - readonly RED_BITS: number; - readonly RENDERBUFFER: number; - readonly RENDERBUFFER_ALPHA_SIZE: number; - readonly RENDERBUFFER_BINDING: number; - readonly RENDERBUFFER_BLUE_SIZE: number; - readonly RENDERBUFFER_DEPTH_SIZE: number; - readonly RENDERBUFFER_GREEN_SIZE: number; - readonly RENDERBUFFER_HEIGHT: number; - readonly RENDERBUFFER_INTERNAL_FORMAT: number; - readonly RENDERBUFFER_RED_SIZE: number; - readonly RENDERBUFFER_STENCIL_SIZE: number; - readonly RENDERBUFFER_WIDTH: number; - readonly RENDERER: number; - readonly REPEAT: number; - readonly REPLACE: number; - readonly RGB: number; - readonly RGB565: number; - readonly RGB5_A1: number; - readonly RGBA: number; - readonly RGBA4: number; - readonly SAMPLER_2D: number; - readonly SAMPLER_CUBE: number; - readonly SAMPLES: number; - readonly SAMPLE_ALPHA_TO_COVERAGE: number; - readonly SAMPLE_BUFFERS: number; - readonly SAMPLE_COVERAGE: number; - readonly SAMPLE_COVERAGE_INVERT: number; - readonly SAMPLE_COVERAGE_VALUE: number; - readonly SCISSOR_BOX: number; - readonly SCISSOR_TEST: number; - readonly SHADER_TYPE: number; - readonly SHADING_LANGUAGE_VERSION: number; - readonly SHORT: number; - readonly SRC_ALPHA: number; - readonly SRC_ALPHA_SATURATE: number; - readonly SRC_COLOR: number; - readonly STATIC_DRAW: number; - readonly STENCIL_ATTACHMENT: number; - readonly STENCIL_BACK_FAIL: number; - readonly STENCIL_BACK_FUNC: number; - readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; - readonly STENCIL_BACK_PASS_DEPTH_PASS: number; - readonly STENCIL_BACK_REF: number; - readonly STENCIL_BACK_VALUE_MASK: number; - readonly STENCIL_BACK_WRITEMASK: number; - readonly STENCIL_BITS: number; - readonly STENCIL_BUFFER_BIT: number; - readonly STENCIL_CLEAR_VALUE: number; - readonly STENCIL_FAIL: number; - readonly STENCIL_FUNC: number; - readonly STENCIL_INDEX: number; - readonly STENCIL_INDEX8: number; - readonly STENCIL_PASS_DEPTH_FAIL: number; - readonly STENCIL_PASS_DEPTH_PASS: number; - readonly STENCIL_REF: number; - readonly STENCIL_TEST: number; - readonly STENCIL_VALUE_MASK: number; - readonly STENCIL_WRITEMASK: number; - readonly STREAM_DRAW: number; - readonly SUBPIXEL_BITS: number; - readonly TEXTURE: number; - readonly TEXTURE0: number; - readonly TEXTURE1: number; - readonly TEXTURE10: number; - readonly TEXTURE11: number; - readonly TEXTURE12: number; - readonly TEXTURE13: number; - readonly TEXTURE14: number; - readonly TEXTURE15: number; - readonly TEXTURE16: number; - readonly TEXTURE17: number; - readonly TEXTURE18: number; - readonly TEXTURE19: number; - readonly TEXTURE2: number; - readonly TEXTURE20: number; - readonly TEXTURE21: number; - readonly TEXTURE22: number; - readonly TEXTURE23: number; - readonly TEXTURE24: number; - readonly TEXTURE25: number; - readonly TEXTURE26: number; - readonly TEXTURE27: number; - readonly TEXTURE28: number; - readonly TEXTURE29: number; - readonly TEXTURE3: number; - readonly TEXTURE30: number; - readonly TEXTURE31: number; - readonly TEXTURE4: number; - readonly TEXTURE5: number; - readonly TEXTURE6: number; - readonly TEXTURE7: number; - readonly TEXTURE8: number; - readonly TEXTURE9: number; - readonly TEXTURE_2D: number; - readonly TEXTURE_BINDING_2D: number; - readonly TEXTURE_BINDING_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; - readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; - readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; - readonly TEXTURE_MAG_FILTER: number; - readonly TEXTURE_MIN_FILTER: number; - readonly TEXTURE_WRAP_S: number; - readonly TEXTURE_WRAP_T: number; - readonly TRIANGLES: number; - readonly TRIANGLE_FAN: number; - readonly TRIANGLE_STRIP: number; - readonly UNPACK_ALIGNMENT: number; - readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; - readonly UNPACK_FLIP_Y_WEBGL: number; - readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; - readonly UNSIGNED_BYTE: number; - readonly UNSIGNED_INT: number; - readonly UNSIGNED_SHORT: number; - readonly UNSIGNED_SHORT_4_4_4_4: number; - readonly UNSIGNED_SHORT_5_5_5_1: number; - readonly UNSIGNED_SHORT_5_6_5: number; - readonly VALIDATE_STATUS: number; - readonly VENDOR: number; - readonly VERSION: number; - readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; - readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; - readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; - readonly VERTEX_ATTRIB_ARRAY_POINTER: number; - readonly VERTEX_ATTRIB_ARRAY_SIZE: number; - readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; - readonly VERTEX_ATTRIB_ARRAY_TYPE: number; - readonly VERTEX_SHADER: number; - readonly VIEWPORT: number; - readonly ZERO: number; -}; - interface WebGLShader extends WebGLObject { } @@ -15799,9 +16113,9 @@ declare var WebGLShader: { }; interface WebGLShaderPrecisionFormat { - readonly precision: number; - readonly rangeMax: number; - readonly rangeMin: number; + readonly precision: GLint; + readonly rangeMax: GLint; + readonly rangeMin: GLint; } declare var WebGLShaderPrecisionFormat: { @@ -15900,7 +16214,7 @@ declare var WheelEvent: { readonly DOM_DELTA_PIXEL: number; }; -interface WindowEventMap extends GlobalEventHandlersEventMap { +interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHandlersEventMap { "abort": UIEvent; "afterprint": Event; "beforeprint": Event; @@ -15911,7 +16225,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "change": Event; "click": MouseEvent; "compassneedscalibration": Event; - "contextmenu": PointerEvent; + "contextmenu": MouseEvent; "dblclick": MouseEvent; "devicelight": DeviceLightEvent; "devicemotion": DeviceMotionEvent; @@ -15946,7 +16260,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "mouseout": MouseEvent; "mouseover": MouseEvent; "mouseup": MouseEvent; - "mousewheel": WheelEvent; + "mousewheel": Event; "MSGestureChange": Event; "MSGestureDoubleTap": Event; "MSGestureEnd": Event; @@ -15999,7 +16313,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "waiting": Event; } -interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch { +interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch, WindowOrWorkerGlobalScope, WindowEventHandlers { Blob: typeof Blob; URL: typeof URL; URLSearchParams: typeof URLSearchParams; @@ -16013,7 +16327,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly devicePixelRatio: number; readonly doNotTrack: string; readonly document: Document; - event: Event | undefined; + readonly event: Event | undefined; /** @deprecated */ readonly external: External; readonly frameElement: Element; @@ -16027,56 +16341,14 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly locationbar: BarProp; readonly menubar: BarProp; readonly msContentScript: ExtensionScriptApis; - readonly msCredentials: MSCredentials; name: string; readonly navigator: Navigator; offscreenBuffering: string | boolean; - onabort: ((this: Window, ev: UIEvent) => any) | null; - onafterprint: ((this: Window, ev: Event) => any) | null; - onbeforeprint: ((this: Window, ev: Event) => any) | null; - onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; - onblur: ((this: Window, ev: FocusEvent) => any) | null; - oncanplay: ((this: Window, ev: Event) => any) | null; - oncanplaythrough: ((this: Window, ev: Event) => any) | null; - onchange: ((this: Window, ev: Event) => any) | null; - onclick: ((this: Window, ev: MouseEvent) => any) | null; oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; - oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; - ondblclick: ((this: Window, ev: MouseEvent) => any) | null; ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; - ondrag: ((this: Window, ev: DragEvent) => any) | null; - ondragend: ((this: Window, ev: DragEvent) => any) | null; - ondragenter: ((this: Window, ev: DragEvent) => any) | null; - ondragleave: ((this: Window, ev: DragEvent) => any) | null; - ondragover: ((this: Window, ev: DragEvent) => any) | null; - ondragstart: ((this: Window, ev: DragEvent) => any) | null; - ondrop: ((this: Window, ev: DragEvent) => any) | null; - ondurationchange: ((this: Window, ev: Event) => any) | null; - onemptied: ((this: Window, ev: Event) => any) | null; - onended: ((this: Window, ev: Event) => any) | null; - onerror: ErrorEventHandler; - onfocus: ((this: Window, ev: FocusEvent) => any) | null; - onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; - oninput: ((this: Window, ev: Event) => any) | null; - oninvalid: ((this: Window, ev: Event) => any) | null; - onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; - onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; - onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; - onload: ((this: Window, ev: Event) => any) | null; - onloadeddata: ((this: Window, ev: Event) => any) | null; - onloadedmetadata: ((this: Window, ev: Event) => any) | null; - onloadstart: ((this: Window, ev: Event) => any) | null; - onmessage: ((this: Window, ev: MessageEvent) => any) | null; - onmousedown: ((this: Window, ev: MouseEvent) => any) | null; - onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; - onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; - onmousemove: ((this: Window, ev: MouseEvent) => any) | null; - onmouseout: ((this: Window, ev: MouseEvent) => any) | null; - onmouseover: ((this: Window, ev: MouseEvent) => any) | null; - onmouseup: ((this: Window, ev: MouseEvent) => any) | null; - onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; + onmousewheel: ((this: Window, ev: Event) => any) | null; onmsgesturechange: ((this: Window, ev: Event) => any) | null; onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; onmsgestureend: ((this: Window, ev: Event) => any) | null; @@ -16092,31 +16364,9 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window onmspointerout: ((this: Window, ev: Event) => any) | null; onmspointerover: ((this: Window, ev: Event) => any) | null; onmspointerup: ((this: Window, ev: Event) => any) | null; - onoffline: ((this: Window, ev: Event) => any) | null; - ononline: ((this: Window, ev: Event) => any) | null; + /** @deprecated */ onorientationchange: ((this: Window, ev: Event) => any) | null; - onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; - onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; - onpause: ((this: Window, ev: Event) => any) | null; - onplay: ((this: Window, ev: Event) => any) | null; - onplaying: ((this: Window, ev: Event) => any) | null; - onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; - onprogress: ((this: Window, ev: ProgressEvent) => any) | null; - onratechange: ((this: Window, ev: Event) => any) | null; onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; - onreset: ((this: Window, ev: Event) => any) | null; - onresize: ((this: Window, ev: UIEvent) => any) | null; - onscroll: ((this: Window, ev: UIEvent) => any) | null; - onseeked: ((this: Window, ev: Event) => any) | null; - onseeking: ((this: Window, ev: Event) => any) | null; - onselect: ((this: Window, ev: UIEvent) => any) | null; - onstalled: ((this: Window, ev: Event) => any) | null; - onstorage: ((this: Window, ev: StorageEvent) => any) | null; - onsubmit: ((this: Window, ev: Event) => any) | null; - onsuspend: ((this: Window, ev: Event) => any) | null; - ontimeupdate: ((this: Window, ev: Event) => any) | null; - onunload: ((this: Window, ev: Event) => any) | null; - onvolumechange: ((this: Window, ev: Event) => any) | null; onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; onvrdisplayblur: ((this: Window, ev: Event) => any) | null; onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; @@ -16126,8 +16376,8 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; - onwaiting: ((this: Window, ev: Event) => any) | null; opener: any; + /** @deprecated */ readonly orientation: string | number; readonly outerHeight: number; readonly outerWidth: number; @@ -16159,32 +16409,30 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window captureEvents(): void; close(): void; confirm(message?: string): boolean; - createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise; - createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; focus(): void; getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; getSelection(): Selection; - matchMedia(mediaQuery: string): MediaQueryList; - moveBy(x?: number, y?: number): void; - moveTo(x?: number, y?: number): void; + matchMedia(query: string): MediaQueryList; + moveBy(x: number, y: number): void; + moveTo(x: number, y: number): void; msWriteProfilerMark(profilerMarkName: string): void; open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; - postMessage(message: any, targetOrigin: string, transfer?: any[]): void; + postMessage(message: any, targetOrigin: string, transfer?: Transferable[]): void; print(): void; prompt(message?: string, _default?: string): string | null; /** @deprecated */ releaseEvents(): void; requestAnimationFrame(callback: FrameRequestCallback): number; - resizeBy(x?: number, y?: number): void; - resizeTo(x?: number, y?: number): void; + resizeBy(x: number, y: number): void; + resizeTo(x: number, y: number): void; scroll(options?: ScrollToOptions): void; - scroll(x?: number, y?: number): void; + scroll(x: number, y: number): void; scrollBy(options?: ScrollToOptions): void; - scrollBy(x?: number, y?: number): void; + scrollBy(x: number, y: number): void; scrollTo(options?: ScrollToOptions): void; - scrollTo(x?: number, y?: number): void; + scrollTo(x: number, y: number): void; stop(): void; webkitCancelAnimationFrame(handle: number): void; webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; @@ -16215,13 +16463,17 @@ interface WindowEventHandlersEventMap { "beforeprint": Event; "beforeunload": BeforeUnloadEvent; "hashchange": HashChangeEvent; + "languagechange": Event; "message": MessageEvent; + "messageerror": MessageEvent; "offline": Event; "online": Event; "pagehide": PageTransitionEvent; "pageshow": PageTransitionEvent; "popstate": PopStateEvent; + "rejectionhandled": Event; "storage": StorageEvent; + "unhandledrejection": PromiseRejectionEvent; "unload": Event; } @@ -16230,13 +16482,17 @@ interface WindowEventHandlers { onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null; onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null; onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null; + onlanguagechange: ((this: WindowEventHandlers, ev: Event) => any) | null; onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; + onmessageerror: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null; onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null; ononline: ((this: WindowEventHandlers, ev: Event) => any) | null; onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null; onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null; + onrejectionhandled: ((this: WindowEventHandlers, ev: Event) => any) | null; onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null; + onunhandledrejection: ((this: WindowEventHandlers, ev: PromiseRejectionEvent) => any) | null; onunload: ((this: WindowEventHandlers, ev: Event) => any) | null; addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -16250,28 +16506,27 @@ interface WindowLocalStorage { interface WindowOrWorkerGlobalScope { readonly caches: CacheStorage; + readonly crypto: Crypto; readonly indexedDB: IDBFactory; + readonly origin: string; readonly performance: Performance; + atob(data: string): string; + btoa(data: string): string; + clearInterval(handle?: number): void; + clearTimeout(handle?: number): void; + createImageBitmap(image: ImageBitmapSource): Promise; + createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise; fetch(input: RequestInfo, init?: RequestInit): Promise; + queueMicrotask(callback: Function): void; + setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; + setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; } interface WindowSessionStorage { readonly sessionStorage: Storage; } -interface WindowTimers extends WindowTimersExtension { - clearInterval(handle?: number): void; - clearTimeout(handle?: number): void; - setInterval(handler: (...args: any[]) => void, timeout: number): number; - setInterval(handler: any, timeout?: any, ...args: any[]): number; - setTimeout(handler: (...args: any[]) => void, timeout: number): number; - setTimeout(handler: any, timeout?: any, ...args: any[]): number; -} - -interface WindowTimersExtension { - clearImmediate(handle: number): void; - setImmediate(handler: (...args: any[]) => void): number; - setImmediate(handler: any, ...args: any[]): number; +interface WindowTimers { } interface WorkerEventMap extends AbstractWorkerEventMap { @@ -16280,7 +16535,7 @@ interface WorkerEventMap extends AbstractWorkerEventMap { interface Worker extends EventTarget, AbstractWorker { onmessage: ((this: Worker, ev: MessageEvent) => any) | null; - postMessage(message: any, transfer?: any[]): void; + postMessage(message: any, transfer?: Transferable[]): void; terminate(): void; addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -16435,7 +16690,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD. * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. */ - send(body?: Document | BodyInit): void; + send(body?: Document | BodyInit | null): void; /** * Combines a header in author request headers. * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. @@ -16506,7 +16761,7 @@ declare var XMLHttpRequestUpload: { }; interface XMLSerializer { - serializeToString(target: Node): string; + serializeToString(root: Node): string; } declare var XMLSerializer: { @@ -16610,6 +16865,10 @@ declare var webkitRTCPeerConnection: { declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +interface BlobCallback { + (blob: Blob | null): void; +} + interface DecodeErrorCallback { (error: DOMException): void; } @@ -16638,10 +16897,6 @@ interface FunctionStringCallback { (data: string): void; } -interface GenerateAssertionCallback { - (contents: string, origin: string, options: RTCIdentityProviderOptions): Promise; -} - interface IntersectionObserverCallback { (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void; } @@ -16650,10 +16905,6 @@ interface MSLaunchUriCallback { (): void; } -interface MediaQueryListListener { - (mql: MediaQueryList): void; -} - interface MutationCallback { (mutations: MutationRecord[], observer: MutationObserver): void; } @@ -16670,6 +16921,14 @@ interface NotificationPermissionCallback { (permission: NotificationPermission): void; } +interface OnBeforeUnloadEventHandlerNonNull { + (event: Event): string | null; +} + +interface OnErrorEventHandlerNonNull { + (event: Event | string, source?: string, lineno?: number, colno?: number, error?: any): any; +} + interface PerformanceObserverCallback { (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void; } @@ -16694,10 +16953,6 @@ interface RTCStatsCallback { (report: RTCStatsReport): void; } -interface ValidateAssertionCallback { - (assertion: string, origin: string): Promise; -} - interface VoidFunction { (): void; } @@ -16717,7 +16972,6 @@ interface WritableStreamErrorCallback { interface HTMLElementTagNameMap { "a": HTMLAnchorElement; "abbr": HTMLElement; - "acronym": HTMLElement; "address": HTMLElement; "applet": HTMLAppletElement; "area": HTMLAreaElement; @@ -16728,14 +16982,12 @@ interface HTMLElementTagNameMap { "base": HTMLBaseElement; "basefont": HTMLBaseFontElement; "bdo": HTMLElement; - "big": HTMLElement; "blockquote": HTMLQuoteElement; "body": HTMLBodyElement; "br": HTMLBRElement; "button": HTMLButtonElement; "canvas": HTMLCanvasElement; "caption": HTMLTableCaptionElement; - "center": HTMLElement; "cite": HTMLElement; "code": HTMLElement; "col": HTMLTableColElement; @@ -16744,7 +16996,9 @@ interface HTMLElementTagNameMap { "datalist": HTMLDataListElement; "dd": HTMLElement; "del": HTMLModElement; + "details": HTMLDetailsElement; "dfn": HTMLElement; + "dialog": HTMLDialogElement; "dir": HTMLDirectoryElement; "div": HTMLDivElement; "dl": HTMLDListElement; @@ -16775,14 +17029,11 @@ interface HTMLElementTagNameMap { "img": HTMLImageElement; "input": HTMLInputElement; "ins": HTMLModElement; - "isindex": HTMLUnknownElement; "kbd": HTMLElement; - "keygen": HTMLElement; "label": HTMLLabelElement; "legend": HTMLLegendElement; "li": HTMLLIElement; "link": HTMLLinkElement; - "listing": HTMLPreElement; "map": HTMLMapElement; "mark": HTMLElement; "marquee": HTMLMarqueeElement; @@ -16790,9 +17041,6 @@ interface HTMLElementTagNameMap { "meta": HTMLMetaElement; "meter": HTMLMeterElement; "nav": HTMLElement; - "nextid": HTMLUnknownElement; - "nobr": HTMLElement; - "noframes": HTMLElement; "noscript": HTMLElement; "object": HTMLObjectElement; "ol": HTMLOListElement; @@ -16802,7 +17050,6 @@ interface HTMLElementTagNameMap { "p": HTMLParagraphElement; "param": HTMLParamElement; "picture": HTMLPictureElement; - "plaintext": HTMLElement; "pre": HTMLPreElement; "progress": HTMLProgressElement; "q": HTMLQuoteElement; @@ -16817,7 +17064,6 @@ interface HTMLElementTagNameMap { "small": HTMLElement; "source": HTMLSourceElement; "span": HTMLSpanElement; - "strike": HTMLElement; "strong": HTMLElement; "style": HTMLStyleElement; "sub": HTMLElement; @@ -16834,12 +17080,15 @@ interface HTMLElementTagNameMap { "title": HTMLTitleElement; "tr": HTMLTableRowElement; "track": HTMLTrackElement; - "tt": HTMLElement; "u": HTMLElement; "ul": HTMLUListElement; "var": HTMLElement; "video": HTMLVideoElement; "wbr": HTMLElement; +} + +interface HTMLElementDeprecatedTagNameMap { + "listing": HTMLPreElement; "xmp": HTMLPreElement; } @@ -16938,56 +17187,14 @@ declare var location: Location; declare var locationbar: BarProp; declare var menubar: BarProp; declare var msContentScript: ExtensionScriptApis; -declare var msCredentials: MSCredentials; declare const name: never; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; -declare var onabort: ((this: Window, ev: UIEvent) => any) | null; -declare var onafterprint: ((this: Window, ev: Event) => any) | null; -declare var onbeforeprint: ((this: Window, ev: Event) => any) | null; -declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; -declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; -declare var oncanplay: ((this: Window, ev: Event) => any) | null; -declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; -declare var onchange: ((this: Window, ev: Event) => any) | null; -declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; -declare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null; -declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; -declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; -declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; -declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; -declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; -declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; -declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; -declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; -declare var ondurationchange: ((this: Window, ev: Event) => any) | null; -declare var onemptied: ((this: Window, ev: Event) => any) | null; -declare var onended: ((this: Window, ev: Event) => any) | null; -declare var onerror: ErrorEventHandler; -declare var onfocus: ((this: Window, ev: FocusEvent) => any) | null; -declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; -declare var oninput: ((this: Window, ev: Event) => any) | null; -declare var oninvalid: ((this: Window, ev: Event) => any) | null; -declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; -declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; -declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; -declare var onload: ((this: Window, ev: Event) => any) | null; -declare var onloadeddata: ((this: Window, ev: Event) => any) | null; -declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; -declare var onloadstart: ((this: Window, ev: Event) => any) | null; -declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; -declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; -declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; -declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; -declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; -declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; -declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; -declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; -declare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null; +declare var onmousewheel: ((this: Window, ev: Event) => any) | null; declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; @@ -17003,31 +17210,9 @@ declare var onmspointermove: ((this: Window, ev: Event) => any) | null; declare var onmspointerout: ((this: Window, ev: Event) => any) | null; declare var onmspointerover: ((this: Window, ev: Event) => any) | null; declare var onmspointerup: ((this: Window, ev: Event) => any) | null; -declare var onoffline: ((this: Window, ev: Event) => any) | null; -declare var ononline: ((this: Window, ev: Event) => any) | null; +/** @deprecated */ declare var onorientationchange: ((this: Window, ev: Event) => any) | null; -declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; -declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; -declare var onpause: ((this: Window, ev: Event) => any) | null; -declare var onplay: ((this: Window, ev: Event) => any) | null; -declare var onplaying: ((this: Window, ev: Event) => any) | null; -declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; -declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; -declare var onratechange: ((this: Window, ev: Event) => any) | null; declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; -declare var onreset: ((this: Window, ev: Event) => any) | null; -declare var onresize: ((this: Window, ev: UIEvent) => any) | null; -declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; -declare var onseeked: ((this: Window, ev: Event) => any) | null; -declare var onseeking: ((this: Window, ev: Event) => any) | null; -declare var onselect: ((this: Window, ev: UIEvent) => any) | null; -declare var onstalled: ((this: Window, ev: Event) => any) | null; -declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; -declare var onsubmit: ((this: Window, ev: Event) => any) | null; -declare var onsuspend: ((this: Window, ev: Event) => any) | null; -declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; -declare var onunload: ((this: Window, ev: Event) => any) | null; -declare var onvolumechange: ((this: Window, ev: Event) => any) | null; declare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null; declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; @@ -17037,8 +17222,8 @@ declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; -declare var onwaiting: ((this: Window, ev: Event) => any) | null; declare var opener: any; +/** @deprecated */ declare var orientation: string | number; declare var outerHeight: number; declare var outerWidth: number; @@ -17070,57 +17255,227 @@ declare function cancelAnimationFrame(handle: number): void; declare function captureEvents(): void; declare function close(): void; declare function confirm(message?: string): boolean; -declare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise; -declare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; declare function departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void; declare function focus(): void; declare function getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration; declare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList; declare function getSelection(): Selection; -declare function matchMedia(mediaQuery: string): MediaQueryList; -declare function moveBy(x?: number, y?: number): void; -declare function moveTo(x?: number, y?: number): void; +declare function matchMedia(query: string): MediaQueryList; +declare function moveBy(x: number, y: number): void; +declare function moveTo(x: number, y: number): void; declare function msWriteProfilerMark(profilerMarkName: string): void; declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null; -declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void; +declare function postMessage(message: any, targetOrigin: string, transfer?: Transferable[]): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string | null; /** @deprecated */ declare function releaseEvents(): void; declare function requestAnimationFrame(callback: FrameRequestCallback): number; -declare function resizeBy(x?: number, y?: number): void; -declare function resizeTo(x?: number, y?: number): void; +declare function resizeBy(x: number, y: number): void; +declare function resizeTo(x: number, y: number): void; declare function scroll(options?: ScrollToOptions): void; -declare function scroll(x?: number, y?: number): void; +declare function scroll(x: number, y: number): void; declare function scrollBy(options?: ScrollToOptions): void; -declare function scrollBy(x?: number, y?: number): void; +declare function scrollBy(x: number, y: number): void; declare function scrollTo(options?: ScrollToOptions): void; -declare function scrollTo(x?: number, y?: number): void; +declare function scrollTo(x: number, y: number): void; declare function stop(): void; declare function webkitCancelAnimationFrame(handle: number): void; declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; declare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number; declare function toString(): string; -declare function dispatchEvent(evt: Event): boolean; -declare function clearInterval(handle?: number): void; -declare function clearTimeout(handle?: number): void; -declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; -declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; -declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; -declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; -declare function clearImmediate(handle: number): void; -declare function setImmediate(handler: (...args: any[]) => void): number; -declare function setImmediate(handler: any, ...args: any[]): number; +/** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ +declare function dispatchEvent(event: Event): boolean; declare var sessionStorage: Storage; declare var localStorage: Storage; declare var console: Console; +/** + * Fires when the user aborts the download. + * @param ev The event. + */ +declare var onabort: ((this: Window, ev: UIEvent) => any) | null; declare var onanimationcancel: ((this: Window, ev: AnimationEvent) => any) | null; declare var onanimationend: ((this: Window, ev: AnimationEvent) => any) | null; declare var onanimationiteration: ((this: Window, ev: AnimationEvent) => any) | null; declare var onanimationstart: ((this: Window, ev: AnimationEvent) => any) | null; +declare var onauxclick: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ +declare var onblur: ((this: Window, ev: FocusEvent) => any) | null; +declare var oncancel: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ +declare var oncanplay: ((this: Window, ev: Event) => any) | null; +declare var oncanplaythrough: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ +declare var onchange: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ +declare var onclick: ((this: Window, ev: MouseEvent) => any) | null; +declare var onclose: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ +declare var oncontextmenu: ((this: Window, ev: MouseEvent) => any) | null; +declare var oncuechange: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ +declare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ +declare var ondrag: ((this: Window, ev: DragEvent) => any) | null; +/** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ +declare var ondragend: ((this: Window, ev: DragEvent) => any) | null; +/** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ +declare var ondragenter: ((this: Window, ev: DragEvent) => any) | null; +declare var ondragexit: ((this: Window, ev: Event) => any) | null; +/** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ +declare var ondragleave: ((this: Window, ev: DragEvent) => any) | null; +/** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ +declare var ondragover: ((this: Window, ev: DragEvent) => any) | null; +/** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ +declare var ondragstart: ((this: Window, ev: DragEvent) => any) | null; +declare var ondrop: ((this: Window, ev: DragEvent) => any) | null; +/** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ +declare var ondurationchange: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ +declare var onemptied: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the end of playback is reached. + * @param ev The event + */ +declare var onended: ((this: Window, ev: Event) => any) | null; +/** + * Fires when an error occurs during object loading. + * @param ev The event. + */ +declare var onerror: ErrorEventHandler; +/** + * Fires when the object receives focus. + * @param ev The event. + */ +declare var onfocus: ((this: Window, ev: FocusEvent) => any) | null; declare var ongotpointercapture: ((this: Window, ev: PointerEvent) => any) | null; +declare var oninput: ((this: Window, ev: Event) => any) | null; +declare var oninvalid: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user presses a key. + * @param ev The keyboard event + */ +declare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null; +/** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ +declare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null; +/** + * Fires when the user releases a key. + * @param ev The keyboard event + */ +declare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null; +/** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ +declare var onload: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ +declare var onloadeddata: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ +declare var onloadedmetadata: ((this: Window, ev: Event) => any) | null; +declare var onloadend: ((this: Window, ev: ProgressEvent) => any) | null; +/** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ +declare var onloadstart: ((this: Window, ev: Event) => any) | null; declare var onlostpointercapture: ((this: Window, ev: PointerEvent) => any) | null; +/** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ +declare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null; +declare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ +declare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ +declare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ +declare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ +declare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null; +/** + * Occurs when playback is paused. + * @param ev The event. + */ +declare var onpause: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the play method is requested. + * @param ev The event. + */ +declare var onplay: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ +declare var onplaying: ((this: Window, ev: Event) => any) | null; declare var onpointercancel: ((this: Window, ev: PointerEvent) => any) | null; declare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null; declare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null; @@ -17129,6 +17484,60 @@ declare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null; declare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null; declare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null; declare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null; +/** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ +declare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null; +/** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ +declare var onratechange: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the user resets a form. + * @param ev The event. + */ +declare var onreset: ((this: Window, ev: Event) => any) | null; +declare var onresize: ((this: Window, ev: UIEvent) => any) | null; +/** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ +declare var onscroll: ((this: Window, ev: UIEvent) => any) | null; +declare var onsecuritypolicyviolation: ((this: Window, ev: SecurityPolicyViolationEvent) => any) | null; +/** + * Occurs when the seek operation ends. + * @param ev The event. + */ +declare var onseeked: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when the current playback position is moved. + * @param ev The event. + */ +declare var onseeking: ((this: Window, ev: Event) => any) | null; +/** + * Fires when the current selection changes. + * @param ev The event. + */ +declare var onselect: ((this: Window, ev: UIEvent) => any) | null; +/** + * Occurs when the download has stopped. + * @param ev The event. + */ +declare var onstalled: ((this: Window, ev: Event) => any) | null; +declare var onsubmit: ((this: Window, ev: Event) => any) | null; +/** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ +declare var onsuspend: ((this: Window, ev: Event) => any) | null; +/** + * Occurs to indicate the current playback position. + * @param ev The event. + */ +declare var ontimeupdate: ((this: Window, ev: Event) => any) | null; +declare var ontoggle: ((this: Window, ev: Event) => any) | null; declare var ontouchcancel: ((this: Window, ev: TouchEvent) => any) | null; declare var ontouchend: ((this: Window, ev: TouchEvent) => any) | null; declare var ontouchmove: ((this: Window, ev: TouchEvent) => any) | null; @@ -17137,13 +17546,54 @@ declare var ontransitioncancel: ((this: Window, ev: TransitionEvent) => any) | n declare var ontransitionend: ((this: Window, ev: TransitionEvent) => any) | null; declare var ontransitionrun: ((this: Window, ev: TransitionEvent) => any) | null; declare var ontransitionstart: ((this: Window, ev: TransitionEvent) => any) | null; +/** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ +declare var onvolumechange: ((this: Window, ev: Event) => any) | null; +/** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ +declare var onwaiting: ((this: Window, ev: Event) => any) | null; declare var onwheel: ((this: Window, ev: WheelEvent) => any) | null; declare var indexedDB: IDBFactory; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; -declare function fetch(input?: Request | string, init?: RequestInit): Promise; +declare function fetch(input: RequestInfo, init?: RequestInit): Promise; +declare var caches: CacheStorage; +declare var crypto: Crypto; +declare var indexedDB: IDBFactory; +declare var origin: string; +declare var performance: Performance; +declare function atob(data: string): string; +declare function btoa(data: string): string; +declare function clearInterval(handle?: number): void; +declare function clearTimeout(handle?: number): void; +declare function createImageBitmap(image: ImageBitmapSource): Promise; +declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise; +declare function fetch(input: RequestInfo, init?: RequestInit): Promise; +declare function queueMicrotask(callback: Function): void; +declare function setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; +declare function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; declare var sessionStorage: Storage; declare var localStorage: Storage; +declare var onafterprint: ((this: Window, ev: Event) => any) | null; +declare var onbeforeprint: ((this: Window, ev: Event) => any) | null; +declare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null; +declare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null; +declare var onlanguagechange: ((this: Window, ev: Event) => any) | null; +declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null; +declare var onmessageerror: ((this: Window, ev: MessageEvent) => any) | null; +declare var onoffline: ((this: Window, ev: Event) => any) | null; +declare var ononline: ((this: Window, ev: Event) => any) | null; +declare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null; +declare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null; +declare var onrejectionhandled: ((this: Window, ev: Event) => any) | null; +declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; +declare var onunhandledrejection: ((this: Window, ev: PromiseRejectionEvent) => any) | null; +declare var onunload: ((this: Window, ev: Event) => any) | null; declare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; declare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -17153,69 +17603,76 @@ type HeadersInit = Headers | string[][] | Record; type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; type RequestInfo = Request | string; type DOMHighResTimeStamp = number; +type RenderingContext = CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext; +type HTMLOrSVGImageElement = HTMLImageElement | SVGImageElement; +type CanvasImageSource = HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap; +type MessageEventSource = WindowProxy | MessagePort | ServiceWorker; +type HTMLOrSVGScriptElement = HTMLScriptElement | SVGScriptElement; +type ImageBitmapSource = CanvasImageSource | Blob | ImageData; +type OnErrorEventHandler = OnErrorEventHandlerNonNull | null; +type OnBeforeUnloadEventHandler = OnBeforeUnloadEventHandlerNonNull | null; +type TimerHandler = string | Function; type PerformanceEntryList = PerformanceEntry[]; -type PushMessageDataInit = BufferSource | string; type VibratePattern = number | number[]; +type AlgorithmIdentifier = string | Algorithm; +type HashAlgorithmIdentifier = AlgorithmIdentifier; +type BigInteger = Uint8Array; +type NamedCurve = string; +type GLenum = number; +type GLboolean = boolean; +type GLbitfield = number; +type GLint = number; +type GLsizei = number; +type GLintptr = number; +type GLsizeiptr = number; +type GLuint = number; +type GLfloat = number; +type GLclampf = number; +type TexImageSource = ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; +type Float32List = Float32Array | GLfloat[]; +type Int32List = Int32Array | GLint[]; type BufferSource = ArrayBufferView | ArrayBuffer; type DOMTimeStamp = number; +type LineAndPositionSetting = number | AutoKeyword; type FormDataEntryValue = File | string; -type ScrollBehavior = "auto" | "instant" | "smooth"; -type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; -type MouseWheelEvent = WheelEvent; -type ScrollRestoration = "auto" | "manual"; type InsertPosition = "beforebegin" | "afterbegin" | "beforeend" | "afterend"; -type OrientationLockType = "any" | "natural" | "portrait" | "landscape" | "portrait-primary" | "portrait-secondary" | "landscape-primary"| "landscape-secondary"; type IDBValidKey = number | string | Date | BufferSource | IDBArrayKey; -type AlgorithmIdentifier = string | Algorithm; type MutationRecordType = "attributes" | "characterData" | "childList"; -type AAGUID = string; -type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; type ConstrainDouble = number | ConstrainDoubleRange; type ConstrainLong = number | ConstrainLongRange; -type CryptoOperationData = ArrayBufferView; -type GLbitfield = number; -type GLboolean = boolean; -type GLbyte = number; -type GLclampf = number; -type GLenum = number; -type GLfloat = number; -type GLint = number; -type GLintptr = number; -type GLshort = number; -type GLsizei = number; -type GLsizeiptr = number; -type GLubyte = number; -type GLuint = number; -type GLushort = number; type IDBKeyPath = string; -type MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload; -type MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent; -type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; +type Transferable = ArrayBuffer | MessagePort | ImageBitmap; type RTCIceGatherCandidate = RTCIceCandidateDictionary | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; -type USVString = string; -type payloadtype = number; -type MessageEventSource = Window | MessagePort | ServiceWorker; +type MouseWheelEvent = WheelEvent; +type WindowProxy = Window; +type AlignSetting = "start" | "center" | "end" | "left" | "right"; type AnimationPlayState = "idle" | "running" | "paused" | "finished"; type AppendMode = "segments" | "sequence"; type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "suspended" | "running" | "closed"; +type AutoKeyword = "auto"; type AutomationRate = "a-rate" | "k-rate"; type BinaryType = "blob" | "arraybuffer"; type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"; type CanPlayTypeResult = "" | "maybe" | "probably"; +type CanvasDirection = "ltr" | "rtl" | "inherit"; type CanvasFillRule = "nonzero" | "evenodd"; +type CanvasLineCap = "butt" | "round" | "square"; +type CanvasLineJoin = "round" | "bevel" | "miter"; +type CanvasTextAlign = "start" | "end" | "left" | "right" | "center"; +type CanvasTextBaseline = "top" | "hanging" | "middle" | "alphabetic" | "ideographic" | "bottom"; type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type CompositeOperation = "replace" | "add" | "accumulate"; +type DirectionSetting = "" | "rl" | "lr"; type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; type DocumentReadyState = "loading" | "interactive" | "complete"; type EndOfStreamError = "network" | "decode"; -type ExpandGranularity = "character" | "word" | "sentence" | "textedit"; type FillMode = "none" | "forwards" | "backwards" | "both" | "auto"; type GamepadHand = "" | "left" | "right"; type GamepadHapticActuatorType = "vibration"; @@ -17224,15 +17681,14 @@ type GamepadMappingType = "" | "standard"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type ImageSmoothingQuality = "low" | "medium" | "high"; type IterationCompositeOperation = "replace" | "accumulate"; type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; type KeyType = "public" | "private" | "secret"; type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; +type LineAlignSetting = "start" | "center" | "end"; type ListeningState = "inactive" | "active" | "disambiguation"; type MSCredentialType = "FIDO_2_0"; -type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived"; -type MSIceType = "failed" | "direct" | "relay"; -type MSStatsType = "description" | "localclientevent" | "inbound-network" | "outbound-network" | "inbound-payload" | "outbound-payload" | "transportdiagnostics"; type MSTransportType = "Embedded" | "USB" | "NFC" | "BT"; type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny"; type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications"; @@ -17246,12 +17702,15 @@ type NavigationReason = "up" | "down" | "left" | "right"; type NavigationType = "navigate" | "reload" | "back_forward" | "prerender"; type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; +type OrientationLockType = "any" | "natural" | "landscape" | "portrait" | "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary"; +type OrientationType = "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary"; type OscillatorType = "sine" | "square" | "sawtooth" | "triangle" | "custom"; type OverSampleType = "none" | "2x" | "4x"; type PanningModelType = "equalpower" | "HRTF"; type PaymentComplete = "success" | "fail" | "unknown"; type PaymentShippingType = "shipping" | "delivery" | "pickup"; type PlaybackDirection = "normal" | "reverse" | "alternate" | "alternate-reverse"; +type PositionAlignSetting = "line-left" | "center" | "line-right" | "auto"; type PushEncryptionKeyName = "p256dh" | "auth"; type PushPermissionState = "denied" | "granted" | "prompt"; type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle"; @@ -17277,7 +17736,7 @@ type RTCPeerConnectionState = "new" | "connecting" | "connected" | "disconnected type RTCPriorityType = "very-low" | "low" | "medium" | "high"; type RTCRtcpMuxPolicy = "negotiate" | "require"; type RTCRtpTransceiverDirection = "sendrecv" | "sendonly" | "recvonly" | "inactive"; -type RTCSctpTransportState = "new" | "connecting" | "connected" | "closed"; +type RTCSctpTransportState = "connecting" | "connected" | "closed"; type RTCSdpType = "offer" | "pranswer" | "answer" | "rollback"; type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | "have-local-pranswer" | "have-remote-pranswer" | "closed"; type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled"; @@ -17292,16 +17751,24 @@ type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; type RequestRedirect = "follow" | "error" | "manual"; type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ScopedCredentialType = "ScopedCred"; +type ScrollBehavior = "auto" | "instant" | "smooth"; +type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; +type ScrollRestoration = "auto" | "manual"; +type ScrollSetting = "" | "up"; type SelectionMode = "select" | "start" | "end" | "preserve"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type ServiceWorkerUpdateViaCache = "imports" | "all" | "none"; +type ShadowRootMode = "open" | "closed"; +type SpeechRecognitionErrorCode = "no-speech" | "aborted" | "audio-capture" | "network" | "not-allowed" | "service-not-allowed" | "bad-grammar" | "language-not-supported"; +type SpeechSynthesisErrorCode = "canceled" | "interrupted" | "audio-busy" | "audio-hardware" | "network" | "synthesis-unavailable" | "synthesis-failed" | "language-unavailable" | "voice-unavailable" | "text-too-long" | "invalid-argument"; +type SupportedType = "text/html" | "text/xml" | "application/xml" | "application/xhtml+xml" | "image/svg+xml"; type TextTrackKind = "subtitles" | "captions" | "descriptions" | "chapters" | "metadata"; type TextTrackMode = "disabled" | "hidden" | "showing"; type TouchType = "direct" | "stylus"; type Transport = "usb" | "nfc" | "ble"; type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; -type VREye = "left" | "right"; type VideoFacingModeEnum = "user" | "environment" | "left" | "right"; -type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; +type VisibilityState = "hidden" | "visible" | "prerender"; +type WebGLPowerPreference = "default" | "low-power" | "high-performance"; type WorkerType = "classic" | "module"; -type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; \ No newline at end of file +type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/lib/lib.dom.iterable.d.ts b/lib/lib.dom.iterable.d.ts index 1c9c11caba100..0948f70259e23 100644 --- a/lib/lib.dom.iterable.d.ts +++ b/lib/lib.dom.iterable.d.ts @@ -51,10 +51,13 @@ interface DOMStringList { interface DOMTokenList { [Symbol.iterator](): IterableIterator; + entries(): IterableIterator<[number, string]>; + keys(): IterableIterator; + values(): IterableIterator; } interface DataTransferItemList { - [Symbol.iterator](): IterableIterator; + [Symbol.iterator](): IterableIterator; } interface FileList { @@ -87,9 +90,10 @@ interface HTMLCollectionBase { interface HTMLCollectionOf { [Symbol.iterator](): IterableIterator; - entries(): IterableIterator<[number, T]>; - keys(): IterableIterator; - values(): IterableIterator; +} + +interface HTMLFormElement { + [Symbol.iterator](): IterableIterator; } interface HTMLSelectElement { @@ -167,10 +171,34 @@ interface PluginArray { interface RTCStatsReport extends ReadonlyMap { } +interface SVGLengthList { + [Symbol.iterator](): IterableIterator; +} + +interface SVGNumberList { + [Symbol.iterator](): IterableIterator; +} + +interface SVGStringList { + [Symbol.iterator](): IterableIterator; +} + interface SourceBufferList { [Symbol.iterator](): IterableIterator; } +interface SpeechGrammarList { + [Symbol.iterator](): IterableIterator; +} + +interface SpeechRecognitionResult { + [Symbol.iterator](): IterableIterator; +} + +interface SpeechRecognitionResultList { + [Symbol.iterator](): IterableIterator; +} + interface StyleSheetList { [Symbol.iterator](): IterableIterator; } diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index ac73e23d9f620..840fd68278906 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1145,15 +1145,15 @@ interface Array { * Returns a string representation of an array. The elements are converted to string using their toLocalString methods. */ toLocaleString(): string; + /** + * Removes the last element from an array and returns it. + */ + pop(): T | undefined; /** * Appends new elements to an array, and returns the new length of the array. * @param items New elements of the Array. */ push(...items: T[]): number; - /** - * Removes the last element from an array and returns it. - */ - pop(): T | undefined; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 0c13cc8a5553f..2fa70fb2a6bb5 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -27,6 +27,33 @@ interface AddEventListenerOptions extends EventListenerOptions { passive?: boolean; } +interface AesCbcParams extends Algorithm { + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface AesCtrParams extends Algorithm { + counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; + tagLength?: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + interface Algorithm { name: string; } @@ -53,6 +80,15 @@ interface CloseEventInit extends EventInit { wasClean?: boolean; } +interface CryptoKeyPair { + privateKey?: CryptoKey; + publicKey?: CryptoKey; +} + +interface CustomEventInit extends EventInit { + detail?: T; +} + interface DOMMatrix2DInit { a?: number; b?: number; @@ -103,6 +139,22 @@ interface DOMRectInit { y?: number; } +interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + interface ErrorEventInit extends EventInit { colno?: number; error?: any; @@ -129,12 +181,12 @@ interface ExtendableMessageEventInit extends ExtendableEventInit { lastEventId?: string; origin?: string; ports?: MessagePort[]; - source?: Client | ServiceWorker | MessagePort; + source?: Client | ServiceWorker | MessagePort | null; } interface FetchEventInit extends ExtendableEventInit { clientId?: string; - preloadResponse: Promise; + preloadResponse?: Promise; request: Request; resultingClientId?: string; targetClientId?: string; @@ -148,6 +200,16 @@ interface GetNotificationOptions { tag?: string; } +interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; +} + interface IDBIndexParameters { multiEntry?: boolean; unique?: boolean; @@ -155,7 +217,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: string | string[]; + keyPath?: string | string[] | null; } interface IDBVersionChangeEventInit extends EventInit { @@ -163,17 +225,37 @@ interface IDBVersionChangeEventInit extends EventInit { oldVersion?: number; } +interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; +} + interface KeyAlgorithm { name: string; } interface MessageEventInit extends EventInit { - channel?: string; data?: any; lastEventId?: string; origin?: string; ports?: MessagePort[]; - source?: object | null; + source?: MessageEventSource | null; } interface NavigationPreloadState { @@ -209,6 +291,12 @@ interface NotificationOptions { vibrate?: VibratePattern; } +interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + interface PerformanceObserverInit { buffered?: boolean; entryTypes: string[]; @@ -241,7 +329,7 @@ interface PushSubscriptionJSON { } interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | string; + applicationServerKey?: BufferSource | string | null; userVisibleOnly?: boolean; } @@ -263,7 +351,7 @@ interface RequestInit { redirect?: RequestRedirect; referrer?: string; referrerPolicy?: ReferrerPolicy; - signal?: object | null; + signal?: AbortSignal | null; window?: any; } @@ -273,6 +361,33 @@ interface ResponseInit { statusText?: string; } +interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; +} + +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; +} + +interface RsaOaepParams extends Algorithm { + label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; +} + +interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; +} + +interface RsaPssParams extends Algorithm { + saltLength: number; +} + interface StorageEstimate { quota?: number; usage?: number; @@ -296,6 +411,45 @@ interface EventListener { (evt: Event): void; } +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and + * signal to any observers that the associated activity is to be aborted. + */ + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignalEventMap { + "abort": ProgressEvent; +} + +interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false + * otherwise. + */ + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; +}; + interface AbstractWorkerEventMap { "error": ErrorEvent; } @@ -401,11 +555,52 @@ declare var CacheStorage: { new(): CacheStorage; }; +interface CanvasGradient { + /** + * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset + * at one end of the gradient, 1.0 is the offset at the other end. + * Throws an "IndexSizeError" DOMException if the offset + * is out of range. Throws a "SyntaxError" DOMException if + * the color cannot be parsed. + */ + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +}; + +interface CanvasPath { + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + closePath(): void; + ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + rect(x: number, y: number, w: number, h: number): void; +} + +interface CanvasPattern { + /** + * Sets the transformation matrix that will be used when rendering the pattern during a fill or + * stroke painting operation. + */ + setTransform(transform?: DOMMatrix2DInit): void; +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +}; + interface Client { readonly id: string; readonly type: ClientTypes; readonly url: string; - postMessage(message: any, transfer?: any[]): void; + postMessage(message: any, transfer?: Transferable[]): void; } declare var Client: { @@ -463,10 +658,8 @@ interface Console { info(message?: any, ...optionalParams: any[]): void; log(message?: any, ...optionalParams: any[]): void; markTimeline(label?: string): void; - msIsIndependentlyComposed(element: object): boolean; profile(reportName?: string): void; - profileEnd(): void; - select(element: object): void; + profileEnd(reportName?: string): void; table(...tabularData: any[]): void; time(label?: string): void; timeEnd(label?: string): void; @@ -482,11 +675,21 @@ declare var Console: { new(): Console; }; +interface Crypto { + readonly subtle: SubtleCrypto; + getRandomValues(array: T): T; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +}; + interface CryptoKey { readonly algorithm: KeyAlgorithm; readonly extractable: boolean; - readonly type: string; - readonly usages: string[]; + readonly type: KeyType; + readonly usages: KeyUsage[]; } declare var CryptoKey: { @@ -494,6 +697,20 @@ declare var CryptoKey: { new(): CryptoKey; }; +interface CustomEvent extends Event { + /** + * Returns any custom data event was created with. + * Typically used for synthetic events. + */ + readonly detail: T; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void; +} + +declare var CustomEvent: { + prototype: CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; +}; + interface DOMException { readonly code: number; readonly message: string; @@ -754,7 +971,7 @@ interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { interface DedicatedWorkerGlobalScope extends WorkerGlobalScope { onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; close(): void; - postMessage(message: any, transfer?: any[]): void; + postMessage(message: any, transfer?: Transferable[]): void; addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -791,32 +1008,65 @@ interface ErrorEvent extends Event { readonly filename: string; readonly lineno: number; readonly message: string; - initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; } declare var ErrorEvent: { prototype: ErrorEvent; - new(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent; + new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent; }; interface Event { + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + */ readonly bubbles: boolean; cancelBubble: boolean; readonly cancelable: boolean; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + */ readonly composed: boolean; + /** + * Returns the object whose event listener's callback is currently being + * invoked. + */ readonly currentTarget: EventTarget | null; readonly defaultPrevented: boolean; readonly eventPhase: number; + /** + * Returns true if event was dispatched by the user agent, and + * false otherwise. + */ readonly isTrusted: boolean; returnValue: boolean; readonly srcElement: object | null; + /** + * Returns the object to which event is dispatched (its target). + */ readonly target: EventTarget | null; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to + * the time origin. + */ readonly timeStamp: number; + /** + * Returns the type of event, e.g. + * "click", "hashchange", or + * "submit". + */ readonly type: string; - deepPath(): EventTarget[]; + composedPath(): EventTarget[]; initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; preventDefault(): void; + /** + * Invoking this method prevents event from reaching + * any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any + * other objects. + */ stopImmediatePropagation(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + */ stopPropagation(): void; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; @@ -826,7 +1076,7 @@ interface Event { declare var Event: { prototype: Event; - new(typeArg: string, eventInitDict?: EventInit): Event; + new(type: string, eventInitDict?: EventInit): Event; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; @@ -860,9 +1110,26 @@ interface EventSourceInit { } interface EventTarget { + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * The options argument sets listener-specific options. For compatibility this can be a + * boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in §2.8 Observing event listeners. + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will + * be removed. + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + */ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; - dispatchEvent(evt: Event): boolean; - removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; + /** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ + dispatchEvent(event: Event): boolean; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + */ + removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; } declare var EventTarget: { @@ -992,11 +1259,11 @@ interface FormData { declare var FormData: { prototype: FormData; - new(form?: object): FormData; + new(): FormData; }; interface GlobalFetch { - fetch(input?: Request | string, init?: RequestInit): Promise; + fetch(input: RequestInfo, init?: RequestInit): Promise; } interface Headers { @@ -1061,13 +1328,13 @@ interface IDBCursor { * Delete the record pointed at by the cursor with a new value. * If successful, request's result will be undefined. */ - delete(): IDBRequest; + delete(): IDBRequest; /** * Updated the record pointed at by the cursor with a new value. * Throws a "DataError" DOMException if the effective object store uses in-line keys and the key would have changed. * If successful, request's result will be the record's key. */ - update(value: any): IDBRequest; + update(value: any): IDBRequest; } declare var IDBCursor: { @@ -1189,40 +1456,40 @@ interface IDBIndex { * If successful, request's result will be the * count. */ - count(key?: IDBValidKey | IDBKeyRange): IDBRequest; + count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the value of the first record matching the * given key or key range in query. * If successful, request's result will be the value, or undefined if there was no matching record. */ - get(key: IDBValidKey | IDBKeyRange): IDBRequest; + get(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). * If successful, request's result will be an Array of the values. */ - getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). * If successful, request's result will be an Array of the keys. */ - getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the * given key or key range in query. * If successful, request's result will be the key, or undefined if there was no matching record. */ - getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; + getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Opens a cursor over the records matching query, * ordered by direction. If query is null, all records in index are matched. * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records. */ - openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched. * If successful, request's result will be an IDBCursor, or null if there were no matching records. */ - openKeyCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + openKeyCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; } declare var IDBIndex: { @@ -1301,19 +1568,19 @@ interface IDBObjectStore { * Returns the associated transaction. */ readonly transaction: IDBTransaction; - add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; + add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Deletes all records in store. * If successful, request's result will * be undefined. */ - clear(): IDBRequest; + clear(): IDBRequest; /** * Retrieves the number of records matching the * given key or key range in query. * If successful, request's result will be the count. */ - count(key?: IDBValidKey | IDBKeyRange): IDBRequest; + count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be * satisfied with the data already in store the upgrade @@ -1328,7 +1595,7 @@ interface IDBObjectStore { * If successful, request's result will * be undefined. */ - delete(key: IDBValidKey | IDBKeyRange): IDBRequest; + delete(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Deletes the index in store with the given name. * Throws an "InvalidStateError" DOMException if not called within an upgrade @@ -1340,41 +1607,41 @@ interface IDBObjectStore { * given key or key range in query. * If successful, request's result will be the value, or undefined if there was no matching record. */ - get(query: IDBValidKey | IDBKeyRange): IDBRequest; + get(query: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the * given key or key range in query (up to count if given). * If successful, request's result will * be an Array of the values. */ - getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; /** * Retrieves the keys of records matching the * given key or key range in query (up to count if given). * If successful, request's result will * be an Array of the keys. */ - getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; + getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the * given key or key range in query. * If successful, request's result will be the key, or undefined if there was no matching record. */ - getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; + getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; index(name: string): IDBIndex; /** * Opens a cursor over the records matching query, * ordered by direction. If query is null, all records in store are matched. * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records. */ - openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched. * If successful, request's result will be an IDBCursor pointing at the first matching record, or * null if there were no matching records. */ - openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; - put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; + openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest; + put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest; } declare var IDBObjectStore: { @@ -1387,7 +1654,7 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap { "upgradeneeded": IDBVersionChangeEvent; } -interface IDBOpenDBRequest extends IDBRequest { +interface IDBOpenDBRequest extends IDBRequest { onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null; onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null; addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -1406,14 +1673,14 @@ interface IDBRequestEventMap { "success": Event; } -interface IDBRequest extends EventTarget { +interface IDBRequest extends EventTarget { /** * When a request is completed, returns the error (a DOMException), or null if the request succeeded. Throws * a "InvalidStateError" DOMException if the request is still pending. */ readonly error: DOMException | null; - onerror: ((this: IDBRequest, ev: Event) => any) | null; - onsuccess: ((this: IDBRequest, ev: Event) => any) | null; + onerror: ((this: IDBRequest, ev: Event) => any) | null; + onsuccess: ((this: IDBRequest, ev: Event) => any) | null; /** * Returns "pending" until a request is complete, * then returns "done". @@ -1424,7 +1691,7 @@ interface IDBRequest extends EventTarget { * or undefined if the request failed. Throws a * "InvalidStateError" DOMException if the request is still pending. */ - readonly result: any; + readonly result: T; /** * Returns the IDBObjectStore, IDBIndex, or IDBCursor the request was made against, or null if is was an open * request. @@ -1435,9 +1702,9 @@ interface IDBRequest extends EventTarget { * If this as an open request, then it returns an upgrade transaction while it is running, or null otherwise. */ readonly transaction: IDBTransaction | null; - addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } @@ -1508,11 +1775,27 @@ declare var IDBVersionChangeEvent: { }; interface ImageBitmap { + /** + * Returns the intrinsic height of the image, in CSS + * pixels. + */ readonly height: number; + /** + * Returns the intrinsic width of the image, in CSS + * pixels. + */ readonly width: number; + /** + * Releases imageBitmap's underlying bitmap data. + */ close(): void; } +declare var ImageBitmap: { + prototype: ImageBitmap; + new(): ImageBitmap; +}; + interface ImageBitmapOptions { colorSpaceConversion?: "none" | "default"; imageOrientation?: "none" | "flipY"; @@ -1523,6 +1806,17 @@ interface ImageBitmapOptions { } interface ImageData { + /** + * Returns the one-dimensional array containing the data in RGBA order, as integers in the + * range 0 to 255. + */ + readonly data: Uint8ClampedArray; + /** + * Returns the actual dimensions of the data in the ImageData object, in + * pixels. + */ + readonly height: number; + readonly width: number; } declare var ImageData: { @@ -1542,11 +1836,31 @@ declare var MessageChannel: { }; interface MessageEvent extends Event { + /** + * Returns the data of the message. + */ readonly data: any; + /** + * Returns the last event ID string, for + * server-sent events. + */ + readonly lastEventId: string; + /** + * Returns the origin of the message, for server-sent events and + * cross-document messaging. + */ readonly origin: string; + /** + * Returns the MessagePort array sent with the message, for cross-document + * messaging and channel messaging. + */ readonly ports: ReadonlyArray; - readonly source: MessageEventSource; - initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: object): void; + /** + * Returns the WindowProxy of the source window, for cross-document + * messaging, and the MessagePort being attached, in the connect event fired at + * SharedWorkerGlobalScope objects. + */ + readonly source: MessageEventSource | null; } declare var MessageEvent: { @@ -1573,7 +1887,7 @@ interface MessagePort extends EventTarget { * transfer contains duplicate objects or port, or if message * could not be cloned. */ - postMessage(message: any, transfer?: any[]): void; + postMessage(message: any, transfer?: Transferable[]): void; /** * Begins dispatching messages received on the port. */ @@ -1680,6 +1994,15 @@ declare var NotificationEvent: { new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; }; +interface Path2D extends CanvasPath { + addPath(path: Path2D, transform?: DOMMatrix2DInit): void; +} + +declare var Path2D: { + prototype: Path2D; + new(path?: Path2D | string): Path2D; +}; + interface PerformanceEventMap { "resourcetimingbufferfull": Event; } @@ -1798,7 +2121,7 @@ declare var ProgressEvent: { }; interface PromiseRejectionEvent extends Event { - readonly promise: PromiseLike; + readonly promise: Promise; readonly reason: any; } @@ -1968,7 +2291,7 @@ interface Request extends Body { * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort * event handler. */ - readonly signal: object; + readonly signal: AbortSignal; /** * Returns the URL of request as a string. */ @@ -2008,7 +2331,7 @@ interface ServiceWorker extends EventTarget, AbstractWorker { onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; readonly scriptURL: string; readonly state: ServiceWorkerState; - postMessage(message: any, transfer?: any[]): void; + postMessage(message: any, transfer?: Transferable[]): void; addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -2124,6 +2447,32 @@ declare var StorageManager: { new(): StorageManager; }; +interface SubtleCrypto { + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +}; + interface SyncEvent extends ExtendableEvent { readonly lastChance: boolean; readonly tag: string; @@ -2313,13 +2662,31 @@ interface WindowConsole { readonly console: Console; } +interface WindowOrWorkerGlobalScope { + readonly caches: CacheStorage; + readonly crypto: Crypto; + readonly indexedDB: IDBFactory; + readonly origin: string; + readonly performance: Performance; + atob(data: string): string; + btoa(data: string): string; + clearInterval(handle?: number): void; + clearTimeout(handle?: number): void; + createImageBitmap(image: ImageBitmapSource): Promise; + createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise; + fetch(input: RequestInfo, init?: RequestInit): Promise; + queueMicrotask(callback: Function): void; + setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; + setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; +} + interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; } interface Worker extends EventTarget, AbstractWorker { onmessage: ((this: Worker, ev: MessageEvent) => any) | null; - postMessage(message: any, transfer?: any[]): void; + postMessage(message: any, transfer?: Transferable[]): void; terminate(): void; addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -2336,15 +2703,13 @@ interface WorkerGlobalScopeEventMap { "error": ErrorEvent; } -interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, GlobalFetch { +interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, GlobalFetch, WindowOrWorkerGlobalScope { readonly caches: CacheStorage; readonly isSecureContext: boolean; readonly location: WorkerLocation; onerror: ((this: WorkerGlobalScope, ev: ErrorEvent) => any) | null; readonly performance: Performance; readonly self: WorkerGlobalScope; - createImageBitmap(image: ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise; - createImageBitmap(image: ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; msWriteProfilerMark(profilerMarkName: string): void; addEventListener(type: K, listener: (this: WorkerGlobalScope, ev: WorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -2388,13 +2753,7 @@ interface WorkerUtils extends WindowBase64 { readonly indexedDB: IDBFactory; readonly msIndexedDB: IDBFactory; readonly navigator: WorkerNavigator; - clearImmediate(handle: number): void; - clearInterval(handle: number): void; - clearTimeout(handle: number): void; importScripts(...urls: string[]): void; - setImmediate(handler: any, ...args: any[]): number; - setInterval(handler: any, timeout?: any, ...args: any[]): number; - setTimeout(handler: any, timeout?: any, ...args: any[]): number; } interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { @@ -2478,7 +2837,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD. * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. */ - send(body?: object | BodyInit): void; + send(body?: BodyInit | null): void; /** * Combines a header in author request headers. * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. @@ -2560,31 +2919,47 @@ interface PerformanceObserverCallback { declare var onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; declare function close(): void; -declare function postMessage(message: any, transfer?: any[]): void; -declare function dispatchEvent(evt: Event): boolean; +declare function postMessage(message: any, transfer?: Transferable[]): void; +/** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ +declare function dispatchEvent(event: Event): boolean; declare var caches: CacheStorage; declare var isSecureContext: boolean; declare var location: WorkerLocation; declare var onerror: ((this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any) | null; declare var performance: Performance; declare var self: WorkerGlobalScope; -declare function createImageBitmap(image: ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise; -declare function createImageBitmap(image: ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function dispatchEvent(evt: Event): boolean; +/** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ +declare function dispatchEvent(event: Event): boolean; declare var indexedDB: IDBFactory; declare var msIndexedDB: IDBFactory; declare var navigator: WorkerNavigator; -declare function clearImmediate(handle: number): void; -declare function clearInterval(handle: number): void; -declare function clearTimeout(handle: number): void; -declare function setImmediate(handler: any, ...args: any[]): number; -declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; -declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; +declare function importScripts(...urls: string[]): void; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; declare var console: Console; -declare function fetch(input?: Request | string, init?: RequestInit): Promise; +declare function fetch(input: RequestInfo, init?: RequestInit): Promise; +declare var caches: CacheStorage; +declare var crypto: Crypto; +declare var indexedDB: IDBFactory; +declare var origin: string; +declare var performance: Performance; +declare function atob(data: string): string; +declare function btoa(data: string): string; +declare function clearInterval(handle?: number): void; +declare function clearTimeout(handle?: number): void; +declare function createImageBitmap(image: ImageBitmapSource): Promise; +declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise; +declare function fetch(input: RequestInfo, init?: RequestInit): Promise; +declare function queueMicrotask(callback: Function): void; +declare function setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; +declare function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number; declare function addEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; declare function removeEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -2594,19 +2969,30 @@ type HeadersInit = Headers | string[][] | Record; type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; type RequestInfo = Request | string; type DOMHighResTimeStamp = number; +type CanvasImageSource = ImageBitmap; +type MessageEventSource = MessagePort | ServiceWorker; +type ImageBitmapSource = CanvasImageSource | Blob | ImageData; +type TimerHandler = string | Function; type PerformanceEntryList = PerformanceEntry[]; type PushMessageDataInit = BufferSource | string; type VibratePattern = number | number[]; +type AlgorithmIdentifier = string | Algorithm; +type HashAlgorithmIdentifier = AlgorithmIdentifier; +type BigInteger = Uint8Array; +type NamedCurve = string; type BufferSource = ArrayBufferView | ArrayBuffer; type DOMTimeStamp = number; type FormDataEntryValue = File | string; type IDBValidKey = number | string | Date | BufferSource | IDBArrayKey; -type MessageEventSource = object | MessagePort | ServiceWorker; +type Transferable = ArrayBuffer | MessagePort | ImageBitmap; type BinaryType = "blob" | "arraybuffer"; type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; +type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk"; +type KeyType = "public" | "private" | "secret"; +type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey"; type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; type PushEncryptionKeyName = "p256dh" | "auth"; @@ -2620,6 +3006,6 @@ type RequestRedirect = "follow" | "error" | "manual"; type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant"; type ServiceWorkerUpdateViaCache = "imports" | "all" | "none"; -type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded"; +type VisibilityState = "hidden" | "visible" | "prerender"; type WorkerType = "classic" | "module"; -type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; \ No newline at end of file +type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 1500a9b598707..e7fcfc6ff5dd8 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -519,7 +519,7 @@ declare namespace ts.server.protocol { /** * Errorcodes we want to get the fixes for. */ - errorCodes?: ReadonlyArray; + errorCodes: ReadonlyArray; } interface GetCombinedCodeFixRequestArgs { scope: GetCombinedCodeFixScope; @@ -591,6 +591,12 @@ declare namespace ts.server.protocol { interface DefinitionRequest extends FileLocationRequest { command: CommandTypes.Definition; } + interface DefinitionAndBoundSpanRequest extends FileLocationRequest { + readonly command: CommandTypes.DefinitionAndBoundSpan; + } + interface DefinitionAndBoundSpanResponse extends Response { + readonly body: DefinitionInfoAndBoundSpan; + } /** * Go to type request; value of command field is * "typeDefinition". Return response giving the file locations that @@ -1879,6 +1885,25 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type LargeFileReferencedEventName = "largeFileReferenced"; + interface LargeFileReferencedEvent extends Event { + event: LargeFileReferencedEventName; + body: LargeFileReferencedEventBody; + } + interface LargeFileReferencedEventBody { + /** + * name of the large file being loaded + */ + file: string; + /** + * size of the file + */ + fileSize: number; + /** + * max file size allowed on the server + */ + maxFileSize: number; + } /** * Arguments for reload request. */ diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index 86442c1764017..509172c0ead8b 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -49,7 +49,7 @@ "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Uma declaração de namespace não pode estar localizada antes de uma classe ou função com a qual ela é mesclada.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Uma declaração de namespace só é permitida e um namespace ou módulo.", "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Uma importação de estilo do namespace não pode ser chamada nem construída e causará uma falha no tempo de execução.", - "A_non_dry_build_would_build_project_0_6357": "Um build não -dry compilaria o projeto '{0}'", + "A_non_dry_build_would_build_project_0_6357": "Um build não -dry criaria o projeto '{0}'", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Um build não -dry excluiria os seguintes arquivos: {0}", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Um inicializador de parâmetro só é permitido em uma implementação de função ou de construtor.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Uma propriedade de parâmetro não pode ser declarada usando um parâmetro rest.", diff --git a/lib/tsc.js b/lib/tsc.js index e3884ccf3bd67..7a7216cf020d4 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -59,7 +59,7 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook }; var ts; (function (ts) { - ts.versionMajorMinor = "3.0"; + ts.versionMajorMinor = "3.1"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { @@ -1444,6 +1444,9 @@ var ts; if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { var candidateNameLowerCase = candidateName.toLowerCase(); if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } return candidate; } if (justCheckExactMatches) { @@ -1632,8 +1635,8 @@ var ts; return function (arg) { return f(arg) || g(arg); }; } ts.or = or; - function assertTypeIsNever(_) { } - ts.assertTypeIsNever = assertTypeIsNever; + function assertType(_) { } + ts.assertType = assertType; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -2057,38 +2060,66 @@ var ts; } ts.onWatchedFileStat = onWatchedFileStat; function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); return createDirectoryWatcher; function createDirectoryWatcher(dirName, callback) { - var watcher = host.watchDirectory(dirName, function (fileName) { - callback(fileName); - updateChildWatches(result, callback); - }); - var result = { - close: function () { - watcher.close(); - result.childWatches.forEach(ts.closeFileWatcher); - result = undefined; - }, + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { dirName: dirName, - childWatches: ts.emptyArray + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } }; - updateChildWatches(result, callback); - return result; } - function updateChildWatches(watcher, callback) { - if (watcher) { - watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + function updateChildWatches(dirName, dirPath) { + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); } } - function watchChildDirectories(parentDir, existingChildWatches, callback) { + function watchChildDirectories(parentDir, existingChildWatches) { var newChildWatches; ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); - return host.filePathComparer(childFullName, host.realpath(childFullName)) === 0 ? childFullName : undefined; - }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); return newChildWatches || ts.emptyArray; function createAndAddChildDirectoryWatcher(childName) { - var result = createDirectoryWatcher(childName, callback); + var result = createDirectoryWatcher(childName); addChildDirectoryWatcher(result); } function addChildDirectoryWatcher(childWatcher) { @@ -2210,18 +2241,16 @@ var ts; process.stdout._handle.setBlocking(true); } }, - base64decode: Buffer.from ? function (input) { - return Buffer.from(input, "base64").toString("utf8"); - } : function (input) { - return new Buffer(input, "base64").toString("utf8"); - }, - base64encode: Buffer.from ? function (input) { - return Buffer.from(input).toString("base64"); - } : function (input) { - return new Buffer(input).toString("base64"); - } + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, }; return nodeSystem; + function bufferFrom(input, encoding) { + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } function isFileSystemCaseSensitive() { if (platform === "win32" || platform === "win64") { return false; @@ -2263,7 +2292,7 @@ var ts; createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : watchDirectoryUsingFsWatch; var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ - filePathComparer: ts.getStringComparer(!useCaseSensitiveFileNames), + useCaseSensitiveFileNames: useCaseSensitiveFileNames, directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, watchDirectory: watchDirectory, @@ -2273,8 +2302,7 @@ var ts; if (recursive) { return watchDirectoryRecursively(directoryName, callback); } - watchDirectory(directoryName, callback); - return undefined; + return watchDirectory(directoryName, callback); }; } function createNonPollingWatchFile() { @@ -2894,6 +2922,8 @@ var ts; Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -2946,7 +2976,7 @@ var ts; Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), - Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), @@ -3162,6 +3192,9 @@ var ts; Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), 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."), @@ -3248,8 +3281,11 @@ var ts; Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), - _0_was_declared_here: diag(2728, ts.DiagnosticCategory.Error, "_0_was_declared_here_2728", "'{0}' was declared here."), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), 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}'."), @@ -3363,6 +3399,7 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -3553,6 +3590,7 @@ var ts; Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -3612,12 +3650,14 @@ var ts; Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), - Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Error, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{0}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -3647,6 +3687,7 @@ var ts; Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), 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."), @@ -3677,6 +3718,7 @@ var ts; Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), @@ -3687,6 +3729,8 @@ var ts; Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -3704,6 +3748,10 @@ var ts; Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), 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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -3766,6 +3814,8 @@ var ts; Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), }; })(ts || (ts = {})); var ts; @@ -5335,6 +5385,7 @@ var ts; } function scanJSDocToken() { startPos = tokenPos = pos; + tokenFlags = 0; if (pos >= end) { return token = 1; } @@ -5353,6 +5404,7 @@ var ts; return token = 57; case 10: case 13: + tokenFlags |= 1; return token = 4; case 42: return token = 39; @@ -5480,6 +5532,7 @@ var ts; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -5585,6 +5638,19 @@ var ts; return undefined; } ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; function forEachEntry(map, callback) { var _a; var iterator = map.entries(); @@ -5775,19 +5841,19 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function prependStatements(to, from) { + function addStatementsAfterPrologue(to, from) { if (from === undefined || from.length === 0) return to; - if (to === undefined) - return from.slice(); - var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); - to.unshift.apply(to, from); - if (prologue) { - to.unshift(prologue); + var statementIndex = 0; + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } } + to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.prependStatements = prependStatements; + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { if (text.charCodeAt(commentPos + 1) === 47 && commentPos + 2 < commentEnd && @@ -5817,7 +5883,7 @@ var ts; if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 303 && node._children.length > 0) { + if (node.kind === 304 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -5892,10 +5958,6 @@ var ts; return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; - function escapeLeadingUnderscores(identifier) { - return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier); - } - ts.escapeLeadingUnderscores = escapeLeadingUnderscores; function makeIdentifierFromModuleName(moduleName) { return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); } @@ -5957,6 +6019,10 @@ var ts; return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -5985,6 +6051,18 @@ var ts; } ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 295: + case 302: + case 291: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { case 158: case 159: @@ -5997,7 +6075,7 @@ var ts; case 207: case 239: case 240: - case 300: + case 301: case 237: case 154: case 155: @@ -6005,16 +6083,13 @@ var ts; case 157: case 194: case 195: - case 295: - case 301: - case 291: return true; default: - ts.assertTypeIsNever(node); + ts.assertType(node); return false; } } - ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { case 247: @@ -6064,11 +6139,11 @@ var ts; return name.escapedText; case 9: case 8: - return escapeLeadingUnderscores(name.text); + return ts.escapeLeadingUnderscores(name.text); case 147: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } ts.getTextOfPropertyName = getTextOfPropertyName; @@ -6209,9 +6284,7 @@ var ts; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { - return n.kind === 181 && - n.argument.kind === 180 && - ts.isStringLiteral(n.argument.literal); + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { @@ -6288,6 +6361,8 @@ var ts; return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case 148: return node === parent.constraint; + case 301: + return node === parent.constraint; case 152: case 151: case 149: @@ -6831,6 +6906,8 @@ var ts; return true; case 209: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 274: + return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); } @@ -6901,12 +6978,15 @@ var ts; } ts.isStringDoubleQuoted = isStringDoubleQuoted; function getDeclarationOfJSInitializer(node) { - if (!isInJavaScriptFile(node) || !node.parent) { + if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + return undefined; + } name = node.parent.name; decl = node.parent; } @@ -7028,8 +7108,12 @@ var ts; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; function getSpecialPropertyAssignmentKind(expr) { - if (!isInJavaScriptFile(expr) || - expr.operatorToken.kind !== 58 || + var special = getSpecialPropertyAssignmentKindWorker(expr); + return special === 5 || isInJavaScriptFile(expr) ? special : 0; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getSpecialPropertyAssignmentKindWorker(expr) { + if (expr.operatorToken.kind !== 58 || !ts.isPropertyAccessExpression(expr.left)) { return 0; } @@ -7039,7 +7123,6 @@ var ts; } return getSpecialPropertyAccessKind(lhs); } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getSpecialPropertyAccessKind(lhs) { if (lhs.expression.kind === 99) { return 4; @@ -7083,6 +7166,14 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 237 || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); } @@ -7159,7 +7250,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 301 || node.kind === 295; + return node.kind === 302 || node.kind === 295; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -7422,7 +7513,10 @@ var ts; } else { var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + return ts.isBinaryExpression(binExp) && + getSpecialPropertyAssignmentKind(binExp) !== 0 && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name; } } default: @@ -7601,12 +7695,10 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isStringOrNumericLiteral(node) { - var kind = node.kind; - return kind === 9 - || kind === 8; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); } - ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); return !!name && isDynamicName(name); @@ -7614,7 +7706,7 @@ var ts; ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { return name.kind === 147 && - !isStringOrNumericLiteral(name.expression) && + !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -7623,22 +7715,24 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71) { - return name.escapedText; - } - if (name.kind === 9 || name.kind === 8) { - return escapeLeadingUnderscores(name.text); - } - if (name.kind === 147) { - var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (nameExpression.kind === 9 || nameExpression.kind === 8) { - return escapeLeadingUnderscores(nameExpression.text); - } + switch (name.kind) { + case 71: + return name.escapedText; + case 9: + case 8: + return ts.escapeLeadingUnderscores(name.text); + case 147: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); } - return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { @@ -7658,7 +7752,7 @@ var ts; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 ? node.escapedText : escapeLeadingUnderscores(node.text); + return node.kind === 71 ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -7771,7 +7865,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 306: + case 307: return 0; case 206: return 1; @@ -8128,27 +8222,30 @@ var ts; return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; - function getOwnEmitOutputFilePath(sourceFile, host, extension) { + function getOwnEmitOutputFilePath(fileName, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; if (compilerOptions.outDir) { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); } else { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); } return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; - function getDeclarationEmitOutputFilePath(sourceFile, host) { - var options = host.getCompilerOptions(); + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { var outputDir = options.declarationDir || options.outDir; var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; return ts.removeFileExtension(path) + ".d.ts"; } - ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; @@ -8169,14 +8266,17 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - var commonSourceDirectory = host.getCommonSourceDirectory(); - var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } - ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); @@ -8246,7 +8346,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 156 || member.kind === 157) + if (ts.isAccessor(member) && hasModifier(member, 32) === hasModifier(accessor, 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -8276,7 +8376,10 @@ var ts; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function getEffectiveTypeAnnotationNode(node) { - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); + var type = node.type; + if (type || !isInJavaScriptFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; function getTypeAnnotationNode(node) { @@ -8284,23 +8387,11 @@ var ts; } ts.getTypeAnnotationNode = getTypeAnnotationNode; function getEffectiveReturnTypeNode(node) { - if (ts.isJSDocSignature(node)) { - return node.type && node.type.typeExpression && node.type.typeExpression.type; - } - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - function getEffectiveTypeParameterDeclarations(node) { - if (ts.isJSDocSignature(node)) { - return ts.emptyArray; - } - if (isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289); - return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); - } - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); - } - ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); } @@ -8945,7 +9036,9 @@ var ts; return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; case 202: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; - return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 58 ? 1 : writeOrReadWrite() + : 0; case 187: return parent.name !== node ? 0 : accessKind(parent); default: @@ -9346,6 +9439,10 @@ var ts; return undefined; } ts.getParseTreeNode = getParseTreeNode; + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; function unescapeLeadingUnderscores(identifier) { var id = identifier; return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; @@ -9416,8 +9513,8 @@ var ts; switch (declaration.kind) { case 71: return declaration; - case 302: - case 296: { + case 303: + case 297: { var name = declaration.name; if (name.kind === 146) { return name.right; @@ -9436,7 +9533,7 @@ var ts; return undefined; } } - case 301: + case 302: return getNameOfJSDocTypedef(declaration); case 252: { var expression = declaration.expression; @@ -9499,6 +9596,10 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; function getJSDocThisTag(node) { return getFirstJSDocTag(node, ts.isJSDocThisTag); } @@ -9529,7 +9630,20 @@ var ts; ts.getJSDocType = getJSDocType; function getJSDocReturnType(node) { var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } } ts.getJSDocReturnType = getJSDocReturnType; function getJSDocTags(node) { @@ -9549,6 +9663,24 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 289); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -9776,7 +9908,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 305) { + while (node.kind === 306) { node = node.expression; } return node; @@ -10170,36 +10302,40 @@ var ts; return node.kind === 294; } ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 296; + } + ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 298; + return node.kind === 299; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 296; + return node.kind === 297; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 297; + return node.kind === 298; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 299; + return node.kind === 300; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 300; + return node.kind === 301; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 301; + return node.kind === 302; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 302; + return node.kind === 303; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 302 || node.kind === 296; + return node.kind === 303 || node.kind === 297; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { @@ -10217,7 +10353,7 @@ var ts; })(ts || (ts = {})); (function (ts) { function isSyntaxList(n) { - return n.kind === 303; + return n.kind === 304; } ts.isSyntaxList = isSyntaxList; function isNode(node) { @@ -10620,8 +10756,8 @@ var ts; case 206: case 210: case 208: + case 307: case 306: - case 305: return true; default: return isUnaryExpressionKind(kind); @@ -10634,11 +10770,11 @@ var ts; } ts.isAssertionExpression = isAssertionExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 305; + return node.kind === 306; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isNotEmittedStatement(node) { - return node.kind === 304; + return node.kind === 305; } ts.isNotEmittedStatement = isNotEmittedStatement; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -10738,9 +10874,9 @@ var ts; || kind === 240 || kind === 148 || kind === 235 - || kind === 301 + || kind === 302 || kind === 295 - || kind === 302; + || kind === 303; } function isDeclarationStatementKind(kind) { return kind === 237 @@ -10775,13 +10911,13 @@ var ts; || kind === 217 || kind === 222 || kind === 229 - || kind === 304 - || kind === 308 - || kind === 307; + || kind === 305 + || kind === 309 + || kind === 308; } function isDeclaration(node) { if (node.kind === 148) { - return node.parent.kind !== 300 || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -10859,7 +10995,7 @@ var ts; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isJSDocNode(node) { - return node.kind >= 281 && node.kind <= 302; + return node.kind >= 281 && node.kind <= 303; } ts.isJSDocNode = isJSDocNode; function isJSDocCommentContainingNode(node) { @@ -10867,7 +11003,7 @@ var ts; } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; function isJSDocTag(node) { - return node.kind >= 292 && node.kind <= 302; + return node.kind >= 292 && node.kind <= 303; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -10887,43 +11023,6 @@ var ts; return !!node.type; } ts.hasType = hasType; - function couldHaveType(node) { - switch (node.kind) { - case 149: - case 151: - case 152: - case 153: - case 154: - case 155: - case 156: - case 157: - case 158: - case 159: - case 160: - case 161: - case 163: - case 164: - case 175: - case 177: - case 179: - case 192: - case 194: - case 195: - case 210: - case 235: - case 237: - case 240: - case 281: - case 284: - case 285: - case 286: - case 287: - case 288: - return true; - } - return false; - } - ts.couldHaveType = couldHaveType; function hasInitializer(node) { return !!node.initializer; } @@ -10933,18 +11032,7 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - switch (node.kind) { - case 265: - case 267: - case 273: - case 274: - case 154: - case 156: - case 157: - return true; - default: - return false; - } + return node.kind === 265 || node.kind === 267 || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; function isTypeReferenceType(node) { @@ -11190,7 +11278,7 @@ var ts; } ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { - return !!(options.declaration && options.declarationMap); + return !!(getEmitDeclarations(options) && options.declarationMap); } ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { @@ -11210,6 +11298,14 @@ var ts; return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + if (oldOptions === newOptions) { + return false; + } + return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || + (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -11322,6 +11418,12 @@ var ts; return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); } ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; function isUrl(path) { return getEncodedRootLength(path) < 0; } @@ -12027,6 +12129,96 @@ var ts; return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); } ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; })(ts || (ts = {})); var ts; (function (ts) { @@ -12419,7 +12611,7 @@ var ts; return visitNode(cbNode, node.expression); case 256: return visitNodes(cbNode, cbNodes, node.decorators); - case 306: + case 307: return visitNodes(cbNode, cbNodes, node.elements); case 258: return visitNode(cbNode, node.openingElement) || @@ -12459,8 +12651,8 @@ var ts; visitNode(cbNode, node.type); case 289: return visitNodes(cbNode, cbNodes, node.tags); - case 296: - case 302: + case 297: + case 303: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -12469,15 +12661,15 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 297: + case 298: return visitNode(cbNode, node.typeExpression); - case 299: + case 300: return visitNode(cbNode, node.typeExpression); case 293: return visitNode(cbNode, node.class); - case 300: - return visitNodes(cbNode, cbNodes, node.typeParameters); case 301: + return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); + case 302: if (node.typeExpression && node.typeExpression.kind === 281) { return visitNode(cbNode, node.typeExpression) || @@ -12490,13 +12682,15 @@ var ts; case 295: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 298: + case 299: + return visitNode(cbNode, node.typeExpression); + case 296: return visitNode(cbNode, node.typeExpression); case 291: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || + ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); case 290: if (node.jsDocPropertyTags) { @@ -12506,7 +12700,7 @@ var ts; } } return; - case 305: + case 306: return visitNode(cbNode, node.expression); } } @@ -13145,7 +13339,7 @@ var ts; return token() === 21 || isLiteralPropertyName(); case 12: return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); - case 17: + case 18: return isLiteralPropertyName(); case 9: return token() === 21 || token() === 24 || isLiteralPropertyName(); @@ -13163,7 +13357,7 @@ var ts; return isIdentifierOrPattern(); case 10: return token() === 26 || token() === 24 || isIdentifierOrPattern(); - case 18: + case 19: return isIdentifier(); case 15: if (token() === 26) { @@ -13172,13 +13366,15 @@ var ts; case 11: return token() === 24 || isStartOfExpression(); case 16: - return isStartOfParameter(); - case 19: + return isStartOfParameter(false); + case 17: + return isStartOfParameter(true); case 20: - return token() === 26 || isStartOfType(); case 21: - return isHeritageClause(); + return token() === 26 || isStartOfType(); case 22: + return isHeritageClause(); + case 23: return ts.tokenIsIdentifierOrKeyword(token()); case 13: return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; @@ -13234,7 +13430,7 @@ var ts; case 6: case 12: case 9: - case 22: + case 23: return token() === 18; case 3: return token() === 18 || token() === 73 || token() === 79; @@ -13242,20 +13438,21 @@ var ts; return token() === 17 || token() === 85 || token() === 108; case 8: return isVariableDeclaratorListTerminator(); - case 18: + case 19: return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; case 11: return token() === 20 || token() === 25; case 15: - case 20: + case 21: case 10: return token() === 22; - case 16: case 17: + case 16: + case 18: return token() === 20 || token() === 22; - case 19: + case 20: return token() !== 26; - case 21: + case 22: return token() === 17 || token() === 18; case 13: return token() === 29 || token() === 41; @@ -13278,7 +13475,7 @@ var ts; return false; } function isInSomeParsingContext() { - for (var kind = 0; kind < 23; kind++) { + for (var kind = 0; kind < 24; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, true) || isListTerminator(kind)) { return true; @@ -13362,14 +13559,15 @@ var ts; return isReusableTypeMember(node); case 8: return isReusableVariableDeclaration(node); + case 17: case 16: return isReusableParameter(node); - case 17: + case 18: return false; + case 22: + case 19: case 21: - case 18: case 20: - case 19: case 11: case 12: case 7: @@ -13488,7 +13686,7 @@ var ts; case 1: return ts.Diagnostics.Declaration_or_statement_expected; case 2: return ts.Diagnostics.case_or_default_expected; case 3: return ts.Diagnostics.Statement_expected; - case 17: + case 18: case 4: return ts.Diagnostics.Property_or_signature_expected; case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6: return ts.Diagnostics.Enum_member_expected; @@ -13499,12 +13697,13 @@ var ts; case 11: return ts.Diagnostics.Argument_expression_expected; case 12: return ts.Diagnostics.Property_assignment_expected; case 15: return ts.Diagnostics.Expression_or_comma_expected; + case 17: return ts.Diagnostics.Parameter_declaration_expected; case 16: return ts.Diagnostics.Parameter_declaration_expected; - case 18: return ts.Diagnostics.Type_parameter_declaration_expected; - case 19: return ts.Diagnostics.Type_argument_expected; - case 20: return ts.Diagnostics.Type_expected; - case 21: return ts.Diagnostics.Unexpected_token_expected; - case 22: return ts.Diagnostics.Identifier_expected; + case 19: return ts.Diagnostics.Type_parameter_declaration_expected; + case 20: return ts.Diagnostics.Type_argument_expected; + case 21: return ts.Diagnostics.Type_expected; + case 22: return ts.Diagnostics.Unexpected_token_expected; + case 23: return ts.Diagnostics.Identifier_expected; case 13: return ts.Diagnostics.Identifier_expected; case 14: return ts.Diagnostics.Identifier_expected; default: return undefined; @@ -13655,7 +13854,7 @@ var ts; var node = createNode(162); node.typeName = parseEntityName(true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); + node.typeArguments = parseBracketedList(20, parseType, 27, 29); } return finishNode(node); } @@ -13742,7 +13941,7 @@ var ts; } function parseJSDocType() { var dotdotdot = parseOptionalToken(24); - var type = parseType(); + var type = parseTypeOrTypePredicate(); if (dotdotdot) { var variadic = createNode(288, dotdotdot.pos); variadic.type = type; @@ -13777,7 +13976,7 @@ var ts; } function parseTypeParameters() { if (token() === 27) { - return parseBracketedList(18, parseTypeParameter, 27, 29); + return parseBracketedList(19, parseTypeParameter, 27, 29); } } function parseParameterType() { @@ -13786,12 +13985,12 @@ var ts; } return undefined; } - function isStartOfParameter() { + function isStartOfParameter(isJSDocParameter) { return token() === 24 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 || - isStartOfType(true); + isStartOfType(!isJSDocParameter); } function parseParameter() { var node = createNodeWithJSDoc(149); @@ -13848,7 +14047,9 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1)); setAwaitContext(!!(flags & 2)); - signature.parameters = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + signature.parameters = flags & 32 ? + parseDelimitedList(17, parseJSDocParameter) : + parseDelimitedList(16, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return parseExpected(20); @@ -14048,7 +14249,7 @@ var ts; } function parseTupleType() { var node = createNode(168); - node.elementTypes = parseBracketedList(20, parseTupleElementType, 21, 22); + node.elementTypes = parseBracketedList(21, parseTupleElementType, 21, 22); return finishNode(node); } function parseParenthesizedType() { @@ -14200,6 +14401,8 @@ var ts; case 126: case 91: return true; + case 89: + return !inStartOfParameter; case 38: return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19: @@ -14210,7 +14413,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 || isStartOfParameter() || isStartOfType(); + return token() === 20 || isStartOfParameter(false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); @@ -14581,7 +14784,7 @@ var ts; if (ts.isModifierKind(second) && second !== 120 && lookAhead(nextTokenIsIdentifier)) { return 1; } - if (!isIdentifier()) { + if (!isIdentifier() && second !== 99) { return 0; } switch (nextToken()) { @@ -15157,7 +15360,7 @@ var ts; } else { var argument = allowInAnd(parseExpression); - if (ts.isStringOrNumericLiteral(argument)) { + if (ts.isStringOrNumericLiteralLike(argument)) { argument.text = internIdentifier(argument.text); } indexedAccess.argumentExpression = argument; @@ -15224,7 +15427,7 @@ var ts; if (!parseOptional(27)) { return undefined; } - var typeArguments = parseDelimitedList(19, parseType); + var typeArguments = parseDelimitedList(20, parseType); if (!parseExpected(29)) { return undefined; } @@ -16235,7 +16438,7 @@ var ts; } function parseHeritageClauses() { if (isHeritageClause()) { - return parseList(21, parseHeritageClause); + return parseList(22, parseHeritageClause); } return undefined; } @@ -16256,7 +16459,7 @@ var ts; } function tryParseTypeArguments() { return token() === 27 - ? parseBracketedList(19, parseType, 27, 29) + ? parseBracketedList(20, parseType, 27, 29) : undefined; } function isHeritageClause() { @@ -16448,7 +16651,7 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(22, kind === 250 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + node.elements = parseBracketedList(23, kind === 250 ? parseImportSpecifier : parseExportSpecifier, 17, 18); return finishNode(node); } function parseExportSpecifier() { @@ -16623,7 +16826,7 @@ var ts; switch (token()) { case 57: if (state === 0 || state === 1) { - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); addTag(parseTag(indent)); state = 0; margin = undefined; @@ -16673,7 +16876,7 @@ var ts; nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return createJSDocComment(); }); function removeLeadingNewlines(comments) { @@ -16681,8 +16884,8 @@ var ts; comments.shift(); } } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { comments.pop(); } } @@ -16713,13 +16916,30 @@ var ts; nextJSDocToken(); } } + function skipWhitespaceOrAsterisk() { + if (token() === 5 || token() === 4) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 39) || token() === 5 || token() === 4) { + if (token() === 4) { + precedingLineBreak = true; + } + else if (token() === 39) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } function parseTag(indent) { ts.Debug.assert(token() === 57); var atToken = createNode(57, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": @@ -16733,6 +16953,9 @@ var ts; case "this": tag = parseThisTag(atToken, tagName); break; + case "enum": + tag = parseEnumTag(atToken, tagName); + break; case "arg": case "argument": case "param": @@ -16823,7 +17046,7 @@ var ts; tok = nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { @@ -16846,7 +17069,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespace(); + skipWhitespaceOrAsterisk(); return token() === 17 ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -16877,15 +17100,15 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespace(); + skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } var result = target === 1 ? - createNode(302, atToken.pos) : - createNode(296, atToken.pos); + createNode(303, atToken.pos) : + createNode(297, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -16911,7 +17134,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 296 || child.kind === 302) { + if (child.kind === 297 || child.kind === 303) { children = ts.append(children, child); } } @@ -16927,20 +17150,20 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 297; })) { + if (ts.forEach(tags, function (t) { return t.kind === 298; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(297, atToken.pos); + var result = createNode(298, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 299; })) { + if (ts.forEach(tags, function (t) { return t.kind === 300; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(299, atToken.pos); + var result = createNode(300, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(true); @@ -16981,7 +17204,15 @@ var ts; return finishNode(tag); } function parseThisTag(atToken, tagName) { - var tag = createNode(298, atToken.pos); + var tag = createNode(299, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(atToken, tagName) { + var tag = createNode(296, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(true); @@ -16991,7 +17222,7 @@ var ts; function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(301, atToken.pos); + var typedefTag = createNode(302, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); @@ -17004,12 +17235,12 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = scanner.getStartPos(); + var start_3 = atToken.pos; while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290, start_3); } - if (child.kind === 299) { + if (child.kind === 300) { if (childTypeTag) { break; } @@ -17071,7 +17302,7 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(57)) { var tag = parseTag(indent); - if (tag && tag.kind === 297) { + if (tag && tag.kind === 298) { return tag; } } @@ -17116,7 +17347,7 @@ var ts; case 57: if (canParseTag) { var child = tryParseChildTag(target); - if (child && (child.kind === 296 || child.kind === 302) && + if (child && (child.kind === 297 || child.kind === 303) && target !== 4 && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -17184,16 +17415,14 @@ var ts; skipWhitespace(); var typeParameter = createNode(148); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); - skipWhitespace(); finishNode(typeParameter); + skipWhitespace(); typeParameters.push(typeParameter); } while (parseOptionalJsdoc(26)); - if (constraint) { - ts.first(typeParameters).constraint = constraint.type; - } - var result = createNode(300, atToken.pos); + var result = createNode(301, atToken.pos); result.atToken = atToken; result.tagName = tagName; + result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); return result; @@ -17529,6 +17758,7 @@ var ts; function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); } + ts.isDeclarationFileName = isDeclarationFileName; function processCommentPragmas(context, sourceText) { var triviaScanner = ts.createScanner(context.languageVersion, false, 0, sourceText); var pragmas = []; @@ -18035,13 +18265,15 @@ var ts; { name: "noImplicitAny", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type }, { name: "strictNullChecks", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks @@ -18049,6 +18281,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types @@ -18056,6 +18289,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes @@ -18063,6 +18297,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, @@ -18070,6 +18305,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file @@ -18077,6 +18313,7 @@ var ts; { name: "noUnusedLocals", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_locals, @@ -18084,6 +18321,7 @@ var ts; { name: "noUnusedParameters", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_parameters, @@ -18091,6 +18329,7 @@ var ts; { name: "noImplicitReturns", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value @@ -18098,6 +18337,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement @@ -18163,12 +18403,14 @@ var ts; { name: "allowSyntheticDefaultImports", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, { name: "esModuleInterop", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports @@ -18340,6 +18582,7 @@ var ts; { name: "noImplicitUseStrict", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output }, @@ -18378,24 +18621,28 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels }, { name: "allowUnreachableCode", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code }, { name: "suppressExcessPropertyErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, }, { name: "suppressImplicitAnyIndexErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, @@ -18414,6 +18661,7 @@ var ts; { name: "noStrictGenericChecks", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, }, @@ -18881,9 +19129,10 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); - var option = knownOptions ? knownOptions.get(keyText) : undefined; - if (extraKeyDiagnosticMessage && !option) { + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); @@ -19746,9 +19995,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -19947,9 +20196,7 @@ var ts; return perFolderCache; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; - } + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { perModuleNameCache = createPerModuleNameCache(); @@ -19969,35 +20216,38 @@ var ts; return; } directoryPathMap.set(path, result); - var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; - var commonPrefix = getCommonPrefix(path, resolvedFileName); + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); var current = path; - while (true) { + while (current !== commonPrefix) { var parent = ts.getDirectoryPath(current); if (parent === current || directoryPathMap.has(parent)) { break; } directoryPathMap.set(parent, result); current = parent; - if (current === commonPrefix) { - break; - } } } function getCommonPrefix(directory, resolution) { - if (resolution === undefined) { - return undefined; - } var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); var i = 0; - while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { i++; } - var sep = directory.lastIndexOf(ts.directorySeparator, i); - if (sep < 0) { + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { + return undefined; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { return undefined; } - return directory.substr(0, sep); + return directory.substr(0, Math.max(sep, rootLength)); } } } @@ -20046,9 +20296,8 @@ var ts; } if (perFolderCache) { perFolderCache.set(moduleName, result); - var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); - if (perModuleNameCache) { - perModuleNameCache.set(containingDirectory, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); } } } @@ -20199,15 +20448,15 @@ var ts; tryResolve(Extensions.JavaScript) || (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { @@ -20217,16 +20466,12 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - var originalPath = void 0; - if (!compilerOptions.preserveSymlinks && resolvedValue) { - originalPath = resolvedValue.path; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - if (path === originalPath) { - originalPath = undefined; - } - resolvedValue = __assign({}, resolvedValue, { path: path }); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); } - return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -20278,14 +20523,14 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } - var nodeModulesPathPart = "/node_modules/"; + ts.nodeModulesPathPart = "/node_modules/"; function parseNodeModuleFromPath(resolved) { var path = ts.normalizePath(resolved.path); - var idx = path.lastIndexOf(nodeModulesPathPart); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; } - var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); if (path.charCodeAt(indexAfterNodeModules) === 64) { indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); @@ -20598,7 +20843,7 @@ var ts; trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -20607,16 +20852,16 @@ var ts; var failedLookupLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, undefined, false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -20645,7 +20890,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, undefined, true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; function toSearchResult(value) { @@ -20795,10 +21040,10 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; symbol.declarations = ts.append(symbol.declarations, node); - if (symbolFlags & 1955 && !symbol.exports) { + if (symbolFlags & (32 | 384 | 1536 | 3) && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } - if (symbolFlags & 6240 && !symbol.members) { + if (symbolFlags & (32 | 64 | 2048 | 4096) && !symbol.members) { symbol.members = ts.createSymbolTable(); } if (symbolFlags & 67216319) { @@ -20821,7 +21066,7 @@ var ts; } if (name.kind === 147) { var nameExpression = name.expression; - if (ts.isStringOrNumericLiteral(nameExpression)) { + if (ts.isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -20861,7 +21106,7 @@ var ts; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); } function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); @@ -20895,24 +21140,29 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; if (symbol.flags & 384 || includes & 384) { message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; } if (symbol.declarations && symbol.declarations.length) { if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } else { if (symbol.declarations && symbol.declarations.length && (node.kind === 252 && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } } } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); symbol = createSymbol(0, name); } } @@ -21141,7 +21391,7 @@ var ts; case 189: bindCallExpressionFlow(node); break; - case 301: + case 302: case 295: bindJSDocTypeAlias(node); break; @@ -21165,6 +21415,7 @@ var ts; case 71: case 99: case 187: + case 188: return isNarrowableReference(expr); case 189: return hasNarrowableArgument(expr); @@ -21178,10 +21429,11 @@ var ts; return false; } function isNarrowableReference(expr) { - return expr.kind === 71 || - expr.kind === 99 || - expr.kind === 97 || - expr.kind === 187 && isNarrowableReference(expr.expression); + return expr.kind === 71 || expr.kind === 99 || expr.kind === 97 || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -21579,7 +21831,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 221) { addAntecedent(postStatementLabel, currentFlow); @@ -21838,7 +22090,7 @@ var ts; case 194: case 195: case 287: - case 301: + case 302: case 295: case 240: case 179: @@ -22117,13 +22369,25 @@ var ts; errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } + function checkStrictModeLabeledStatement(node) { + if (inStrictMode && options.target >= 2) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } - function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); if (isError) { file.bindDiagnostics.push(diag); } @@ -22211,12 +22475,19 @@ var ts; } return checkStrictModeIdentifier(node); case 187: + case 188: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } + if (ts.isInJavaScriptFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(container, "module")) { + declareSymbol(container.locals, undefined, node.expression, 1 | 134217728, 67216318); + } break; case 202: var specialKind = ts.getSpecialPropertyAssignmentKind(node); @@ -22257,6 +22528,8 @@ var ts; return checkStrictModePrefixUnaryExpression(node); case 229: return checkStrictModeWithStatement(node); + case 231: + return checkStrictModeLabeledStatement(node); case 176: seenThisKeyword = true; return; @@ -22351,20 +22624,20 @@ var ts; } case 243: return updateStrictModeStatementList(node.statements); - case 296: + case 297: if (node.parent.kind === 291) { return bindParameter(node); } if (node.parent.kind !== 290) { break; } - case 302: + case 303: var propTag = node; var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 ? 4 | 16777216 : 4; return declareSymbolAndAddToSymbolTable(propTag, flags, 0); - case 301: + case 302: case 295: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } @@ -22539,6 +22812,10 @@ var ts; } function bindSpecialPropertyAssignment(node) { var lhs = node.left; + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } node.left.parent = node; node.right.parent = node; if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { @@ -22680,7 +22957,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 296 && container.kind !== 291) { + if (node.kind === 297 && container.kind !== 291) { return; } if (inStrictMode && !(node.flags & 4194304)) { @@ -22785,18 +23062,45 @@ var ts; if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { - var isError = ts.unreachableCodeIsError(options) && + var isError_1 = ts.unreachableCodeIsError(options) && !(node.flags & 4194304) && (!ts.isVariableStatement(node) || !!(ts.getCombinedNodeFlags(node.declarationList) & 3) || node.declarationList.declarations.some(function (d) { return !!d.initializer; })); - errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); } } } return true; } } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + function isExecutableStatement(s) { + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 | 2)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 239: + case 240: + return true; + case 242: + return getModuleInstanceState(s) !== 1; + case 241: + return ts.hasModifier(s, 2048); + default: + return false; + } + } function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || ts.isModuleExportsPropertyAccessExpression(node) || @@ -23263,7 +23567,7 @@ var ts; break; case 192: case 210: - case 305: + case 306: transformFlags |= 3; excludeFlags = 536872257; break; @@ -23500,7 +23804,7 @@ var ts; return 940049729; case 192: case 210: - case 305: + case 306: case 193: case 97: return 536872257; @@ -23519,7 +23823,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -23592,7 +23896,7 @@ var ts; ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { - visitType(getConstraintFromTypeParameter(type)); + visitType(getConstraintOfTypeParameter(type)); } function visitUnionOrIntersectionType(type) { ts.forEach(type.types, visitType); @@ -23663,7 +23967,7 @@ var ts; } var t = getTypeOfSymbol(symbol); visitType(t); - if (symbol.flags & 1955) { + if (symbol.exports) { symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { @@ -23737,7 +24041,6 @@ var ts; undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4, "arguments"); var requireSymbol = createSymbol(4, "require"); - var moduleSymbol = createSymbol(4, "module"); var apparentArgumentCount; var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -23775,6 +24078,7 @@ var ts; return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, getReturnTypeOfSignature: getReturnTypeOfSignature, getNullableType: getNullableType, getNonNullableType: getNonNullableType, @@ -23843,6 +24147,10 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); @@ -23853,12 +24161,11 @@ var ts; }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { - var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); - apparentArgumentCount = theArgumentCount; - var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; - apparentArgumentCount = undefined; - return res; + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, true); }, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); @@ -23895,7 +24202,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); @@ -23936,7 +24243,7 @@ var ts; getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentModule: function (node, target) { return getSuggestionForNonexistentModule(node, target); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -23955,6 +24262,9 @@ var ts; return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } var diagnostics; try { cancellationToken = ct; @@ -23970,8 +24280,8 @@ var ts; cancellationToken = undefined; } function addUnusedDiagnostics() { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { - if (!unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } }); @@ -23987,6 +24297,13 @@ var ts; } } }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } var tupleTypes = ts.createMap(); var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); @@ -24040,7 +24357,6 @@ var ts; var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); var globals = ts.createSymbolTable(); var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); @@ -24503,7 +24819,7 @@ var ts; return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + return !!(usage.flags & 2097152) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { @@ -24711,7 +25027,7 @@ var ts; location = location.parent; } break; - case 301: + case 302: case 295: location = ts.getJSDocHost(location); break; @@ -24741,10 +25057,6 @@ var ts; if (ts.isRequireCall(originalLocation.parent, false)) { return requireSymbol; } - if (ts.isIdentifier(originalLocation) && ts.isPropertyAccessExpression(originalLocation.parent) && - originalLocation.escapedText === "module" && originalLocation.parent.name.escapedText === "exports") { - return moduleSymbol; - } } } if (!result) { @@ -24757,9 +25069,13 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { - suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } } if (!suggestion) { @@ -24944,7 +25260,7 @@ var ts; ts.Debug.assert(!!(result.flags & 128)); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } } @@ -25086,9 +25402,13 @@ var ts; if (!symbol) { var moduleName = getFullyQualifiedName(moduleSymbol); var declarationName = ts.declarationNameToString(name); - var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); @@ -25376,6 +25696,12 @@ var ts; var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json") && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -25387,8 +25713,8 @@ var ts; var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; var errorInfo = packageId ? ts.chainDiagnosticMessages(undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0 - : ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)) + ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 + : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } @@ -25528,7 +25854,7 @@ var ts; moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; function visit(symbol) { - if (!(symbol && symbol.flags & 1955 && ts.pushIfUnique(visitedSymbols, symbol))) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { return; } var symbols = ts.cloneMap(symbol.exports); @@ -25567,17 +25893,25 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } - function getContainerOfSymbol(symbol) { + function getContainersOfSymbol(symbol, enclosingDeclaration) { var container = getParentOfSymbol(symbol); if (container) { - return container; + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920, false)) { + return ts.concatenate([container], additionalContainers); + } + return ts.append(additionalContainers, container); } - var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); - if (!candidate) { + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { return undefined; } - var alias = getAliasForSymbolInContainer(candidate, symbol); - return alias ? candidate : undefined; + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export="); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { @@ -25600,9 +25934,7 @@ var ts; } } function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; + return getMergedSymbol(symbol && (symbol.flags & 1048576) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { return !!(symbol.flags & 67216319 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67216319); @@ -25801,54 +26133,67 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319, false); return access.accessibility === 0; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, - }; - } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { return hasAccessibleDeclarations; } - else { - if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { - return { - accessibility: 0 - }; - } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return { + accessibility: 0 + }; } - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getContainerOfSymbol(symbol); } - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920) : undefined, + }; + } + } + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration) { + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; + } + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { return { accessibility: 2, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), errorModuleName: symbolToString(symbolExternalModule) }; } } return { accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 277 && ts.isExternalOrCommonJsModule(declaration)); @@ -25957,7 +26302,8 @@ var ts; function typeToString(type, enclosingDeclaration, flags, writer) { if (flags === void 0) { flags = 1048576 | 16384; } if (writer === void 0) { writer = ts.createTextWriter(""); } - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960, writer); + var noTruncation = compilerOptions.noErrorTruncation || flags & 1; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | (noTruncation ? 1 : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -25965,7 +26311,7 @@ var ts; var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4, typeNode, sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 1 ? undefined : 100; + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } @@ -26010,11 +26356,17 @@ var ts; tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, - inferTypeParameters: undefined + inferTypeParameters: undefined, + approximateLength: 0 }; var resultingNode = cb(context); return context.encounteredError ? undefined : resultingNode; } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1) && context.approximateLength > ts.defaultMaximumTruncationLength; + } function typeToTypeNodeHelper(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); @@ -26026,66 +26378,83 @@ var ts; return undefined; } if (type.flags & 1) { + context.approximateLength += 3; return ts.createKeywordTypeNode(119); } if (type.flags & 2) { return ts.createKeywordTypeNode(142); } if (type.flags & 4) { + context.approximateLength += 6; return ts.createKeywordTypeNode(137); } if (type.flags & 8) { + context.approximateLength += 6; return ts.createKeywordTypeNode(134); } if (type.flags & 16) { + context.approximateLength += 7; return ts.createKeywordTypeNode(122); } if (type.flags & 512 && !(type.flags & 262144)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 67901928, false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 544) { var name = symbolToName(type.symbol, context, 67901928, false); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, undefined); } - if (type.flags & (64)) { + if (type.flags & 64) { + context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); } - if (type.flags & (128)) { + if (type.flags & 128) { + context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 256) { + context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 2048) { if (!(context.flags & 1048576)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; return symbolToTypeNode(type.symbol, context, 67216319); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } + context.approximateLength += 13; return ts.createTypeOperatorNode(141, ts.createKeywordTypeNode(138)); } if (type.flags & 4096) { + context.approximateLength += 4; return ts.createKeywordTypeNode(105); } if (type.flags & 8192) { + context.approximateLength += 9; return ts.createKeywordTypeNode(140); } if (type.flags & 16384) { + context.approximateLength += 4; return ts.createKeywordTypeNode(95); } if (type.flags & 32768) { + context.approximateLength += 5; return ts.createKeywordTypeNode(131); } if (type.flags & 1024) { + context.approximateLength += 6; return ts.createKeywordTypeNode(138); } if (type.flags & 16777216) { + context.approximateLength += 6; return ts.createKeywordTypeNode(135); } if (type.flags & 65536 && type.isThisType) { @@ -26097,6 +26466,7 @@ var ts; context.tracker.reportInaccessibleThisError(); } } + context.approximateLength += 4; return ts.createThis(); } var objectFlags = ts.getObjectFlags(type); @@ -26106,6 +26476,7 @@ var ts; } if (type.flags & 65536 || objectFlags & 3) { if (type.flags & 65536 && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, undefined)); } if (context.flags & 4 && @@ -26114,7 +26485,9 @@ var ts; ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { - return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8), undefined); + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 | 8), undefined); } return type.symbol ? symbolToTypeNode(type.symbol, context, 67901928) @@ -26128,7 +26501,7 @@ var ts; } if (type.flags & (262144 | 524288)) { var types = type.flags & 262144 ? formatUnionTypes(type.types) : type.types; - var typeNodes = mapToTypeNodes(types, context); + var typeNodes = mapToTypeNodes(types, context, true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 ? 171 : 172, typeNodes); return unionOrIntersectionTypeNode; @@ -26146,12 +26519,14 @@ var ts; } if (type.flags & 1048576) { var indexedType = type.type; + context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 2097152) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } if (type.flags & 4194304) { @@ -26162,6 +26537,7 @@ var ts; context.inferTypeParameters = saveInferTypeParameters; var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 8388608) { @@ -26182,6 +26558,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1); } function createAnonymousTypeNode(type) { @@ -26190,7 +26567,7 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { var isInstanceType = type === getInferredClassType(symbol) ? 67901928 : 67216319; return symbolToTypeNode(symbol, context, isInstanceType); } @@ -26205,6 +26582,7 @@ var ts; return symbolToTypeNode(typeAlias, context, 67901928); } else { + context.approximateLength += 3; return ts.createKeywordTypeNode(119); } } @@ -26242,6 +26620,7 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { @@ -26260,6 +26639,7 @@ var ts; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024) ? 0 : 1); } function typeReferenceToTypeNode(type) { @@ -26369,6 +26749,9 @@ var ts; return ids; } function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(undefined, "...", undefined, undefined, undefined)]; + } var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; @@ -26391,8 +26774,10 @@ var ts; if (!properties) { return typeElements; } + var i = 0; for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + i++; if (context.flags & 2048) { if (propertySymbol.flags & 4194304) { continue; @@ -26401,57 +26786,92 @@ var ts; context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); } } - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 && context.flags & 33554432 ? - anyType : getTypeOfSymbol(propertySymbol); - var saveEnclosingDeclaration = context.enclosingDeclaration; - context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024) { - var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 | 1048576, undefined, undefined, true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); - } - } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(undefined, "... " + (properties.length - i) + " more ...", undefined, undefined, undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; } - var propertyName = symbolToName(propertySymbol, context, 67216319, true); - context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; - if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { - var signatures = getSignaturesOfType(propertyType, 0); - for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { - var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - if (propertySymbol.valueDeclaration) { - ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); - } - typeElements.push(methodDeclaration); - } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 && context.flags & 33554432 ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024) { + var decl = ts.first(propertySymbol.declarations); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 | 1048576, undefined, undefined, true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); } - else { - var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048) ? 33554432 : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); - context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132)] : undefined; - var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); - if (propertySymbol.valueDeclaration) { - ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); - } - typeElements.push(propertySignature); + } + } + var propertyName = symbolToName(propertySymbol, context, 67216319, true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; + if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); } + typeElements.push(methodDeclaration); } - return typeElements.length ? typeElements : undefined; + } + else { + var savedFlags = context.flags; + context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048) ? 33554432 : 0; + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, undefined); + if (propertySymbol.valueDeclaration) { + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); } } - function mapToTypeNodes(types, context) { + function mapToTypeNodes(types, context, isBareList) { if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } var result = []; + var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -26468,6 +26888,7 @@ var ts; if (!indexInfo.type && !(context.flags & 2097152)) { context.encounteredError = true; } + context.approximateLength += (name.length + 4); return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(132)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { @@ -26505,6 +26926,7 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119); } + context.approximateLength += 3; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { @@ -26526,14 +26948,14 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 296); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -26553,6 +26975,7 @@ var ts; var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096; var questionToken = isOptional ? ts.createToken(55) : undefined; var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); @@ -26580,15 +27003,17 @@ var ts; return chain; function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128)); - var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents)) { + for (var _i = 0, _a = parents; _i < _a.length; _i++) { + var parent = _a[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } } } } @@ -26596,8 +27021,10 @@ var ts; return accessibleSymbolChain; } if (endOfChain || - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && - !(symbol.flags & (2048 | 4096))) { + !(symbol.flags & (2048 | 4096))) { + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } return [symbol]; } } @@ -26648,22 +27075,25 @@ var ts; } } } - return symbol.escapedName.substring(1, symbol.escapedName.length - 1); - } - else { - if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); - var links = getSymbolLinks(symbol); - var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); - if (!specifier) { - specifier = ts.flatten(ts.moduleSpecifiers.getModuleSpecifiers(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, context.tracker.moduleResolverHost.getSourceFiles(), { importModuleSpecifierPreference: "non-relative" }))[0]; - links.specifierCache = links.specifierCache || ts.createMap(); - links.specifierCache.set(contextFile.path, specifier); + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - return specifier; + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384)); @@ -26671,7 +27101,11 @@ var ts; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); - var lit = ts.createLiteralTypeNode(ts.createLiteral(getSpecifierForModuleSymbol(chain[0], context))); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; if (!nonRootParts || ts.isEntityName(nonRootParts)) { if (nonRootParts) { var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; @@ -26705,6 +27139,7 @@ var ts; context.flags |= 16777216; } var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; if (index === 0) { context.flags ^= 16777216; } @@ -26908,7 +27343,7 @@ var ts; function determineIfDeclarationIsVisible() { switch (node.kind) { case 295: - case 301: + case 302: return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); case 184: return isDeclarationVisible(node.parent.parent); @@ -27033,23 +27468,19 @@ var ts; return -1; } function hasType(target, propertyName) { - if (propertyName === 0) { - return !!getSymbolLinks(target).type; - } - if (propertyName === 2) { - return !!getSymbolLinks(target).declaredType; - } - if (propertyName === 1) { - return !!target.resolvedBaseConstructorType; - } - if (propertyName === 3) { - return !!target.resolvedReturnType; - } - if (propertyName === 4) { - var bc = target.resolvedBaseConstraint; - return !!bc && bc !== circularConstraintType; + switch (propertyName) { + case 0: + return !!getSymbolLinks(target).type; + case 2: + return !!getSymbolLinks(target).declaredType; + case 1: + return !!target.resolvedBaseConstructorType; + case 3: + return !!target.resolvedReturnType; + case 4: + return !!target.immediateBaseConstraint; } - return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + return ts.Debug.assertNever(propertyName); } function popTypeResolution() { resolutionTargets.pop(); @@ -27087,7 +27518,7 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } function isComputedNonLiteralName(name) { - return name.kind === 147 && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 147 && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 24576); }); @@ -27105,10 +27536,9 @@ var ts; } for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; - var inNamesToRemove = names.has(prop.escapedName); - var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); - var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); - if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { + if (!names.has(prop.escapedName) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16)) + && isSpreadableProperty(prop)) { members.set(prop.escapedName, getNonReadonlySymbol(prop)); } } @@ -27282,17 +27712,17 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } - var type = void 0; - if (declaration.symbol.escapedName === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.escapedName === "this" ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } + else if (ts.isInJavaScriptFile(declaration)) { + var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); + if (expandoType) { + return expandoType; + } + } if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); return addOptionality(type, isOptional); @@ -27305,91 +27735,45 @@ var ts; } return undefined; } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); if (specialDeclaration) { - return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var tag = ts.getJSDocTypeTag(specialDeclaration); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); + return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); } - var types = []; - var constructorTypes; var definedInConstructor = false; var definedInMethod = false; - var jsDocType; - var _loop_4 = function (declaration) { - var declarationInConstructor = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; var expression = ts.isBinaryExpression(declaration) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { - return { value: errorType }; + return errorType; } var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); if (special === 4) { - var thisContainer = ts.getThisContainer(expression, false); - declarationInConstructor = thisContainer.kind === 155 || - thisContainer.kind === 237 || - (thisContainer.kind === 194 && !ts.isPrototypePropertyAssignment(thisContainer.parent)); - if (declarationInConstructor) { + if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } else { definedInMethod = true; } } - var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type_1) { - var declarationType = getWidenedType(type_1); - if (!jsDocType) { - jsDocType = declarationType; - } - else if (jsDocType !== errorType && declarationType !== errorType && - !isTypeIdenticalTo(jsDocType, declarationType) && - !(symbol.flags & 67108864)) { - errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); - } - } - else if (!jsDocType && ts.isBinaryExpression(expression)) { - var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); - if (ts.getObjectFlags(type_2) & 16 && - special === 2 && - symbol.escapedName === "export=") { - var exportedType_1 = resolveStructuredTypeMembers(type_2); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); - symbol.exports.forEach(function (s, name) { - if (members_3.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); - } - else { - members_3.set(name, s); - } - }); - type_2 = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); - } - var anyedType = type_2; - if (isEmptyArrayLiteralType(type_2)) { - anyedType = anyArrayType; - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } - } - types.push(anyedType); - if (declarationInConstructor) { - (constructorTypes || (constructorTypes = [])).push(anyedType); - } + jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!jsdocType) { + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); } - }; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var state_2 = _loop_4(declaration); - if (typeof state_2 === "object") - return state_2.value; } - var type = jsDocType; + var type = jsdocType; if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; if (definedInMethod) { var propType = getTypeOfSpecialPropertyOfBaseType(symbol); if (propType) { @@ -27409,6 +27793,88 @@ var ts; } return widened; } + function getJSExpandoObjectType(decl, symbol, init) { + if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384; + return type; + } + function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 131072 && + special === 2 && + symbol.escapedName === "export=") { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384); + return result; + } + if (isEmptyArrayLiteralType(type)) { + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, false); + return thisContainer.kind === 155 || + thisContainer.kind === 237 || + (thisContainer.kind === 194 && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } function getTypeOfSpecialPropertyOfBaseType(specialProperty) { var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { var parent = ts.getThisContainer(d, false).parent; @@ -27520,126 +27986,98 @@ var ts; } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbol.flags & 4194304) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - if (symbol === requireSymbol || symbol === moduleSymbol) { - return links.type = anyType; - } - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; - } - if (declaration.kind === 252) { - return links.type = checkExpression(declaration.expression); - } - if (!pushTypeResolution(symbol, 0)) { - return errorType; - } - var type = getJSSpecialType(symbol, declaration); - if (!type) { - if (ts.isJSDocPropertyLikeTag(declaration) - || ts.isPropertyAccessExpression(declaration) - || ts.isIdentifier(declaration) - || ts.isClassDeclaration(declaration) - || ts.isFunctionDeclaration(declaration) - || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { - if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { - return getTypeOfFuncClassEnumModule(symbol); - } - type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; - } - else if (ts.isPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); - } - else if (ts.isJsxAttribute(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); - } - else if (ts.isShorthandPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0); - } - else if (ts.isObjectLiteralMethod(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0); - } - else if (ts.isParameter(declaration) - || ts.isPropertyDeclaration(declaration) - || ts.isPropertySignature(declaration) - || ts.isVariableDeclaration(declaration) - || ts.isBindingElement(declaration)) { - type = getWidenedTypeForVariableLikeDeclaration(declaration, true); - } - else { - return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); - } - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); } - function getJSSpecialType(symbol, decl) { - if (!ts.isInJavaScriptFile(decl)) { - return undefined; + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + if (symbol.flags & 4194304) { + return getTypeOfPrototypeProperty(symbol); } - else if (ts.isJSDocPropertyLikeTag(decl) && decl.typeExpression) { - return getTypeFromTypeNode(decl.typeExpression.type); + if (symbol === requireSymbol) { + return anyType; } - else if (ts.isBinaryExpression(decl) || - ts.isPropertyAccessExpression(decl) && ts.isBinaryExpression(decl.parent)) { - return getJSInitializerType(decl, symbol, ts.getAssignedJavascriptInitializer(ts.isBinaryExpression(decl) ? decl.left : decl)) || - getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + if (symbol.flags & 134217728) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } - else if (ts.isParameter(decl) - || ts.isPropertyDeclaration(decl) - || ts.isPropertySignature(decl) - || ts.isVariableDeclaration(decl) - || ts.isBindingElement(decl)) { - var isOptional = ts.isParameter(decl) && isJSDocOptionalParameter(decl) || - !ts.isBindingElement(decl) && !ts.isVariableDeclaration(decl) && !!decl.questionToken; - var declaredType = tryGetTypeFromEffectiveTypeNode(decl); - return declaredType && addOptionality(declaredType, isOptional) || - getJSInitializerType(decl, symbol, ts.getDeclaredJavascriptInitializer(decl)) || - getWidenedTypeForVariableLikeDeclaration(decl, true); + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; } - } - function getJSInitializerType(decl, symbol, init) { - if (init && ts.isInJavaScriptFile(init) && ts.isObjectLiteralExpression(init)) { - var exports_1 = ts.createSymbolTable(); - while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { - var s_1 = getSymbolOfNode(decl); - if (s_1 && ts.hasEntries(s_1.exports)) { - mergeSymbolTable(exports_1, s_1.exports); - } - decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; - } - var s = getSymbolOfNode(decl); - if (s && ts.hasEntries(s.exports)) { - mergeSymbolTable(exports_1, s.exports); - } - return createAnonymousType(symbol, exports_1, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } + if (declaration.kind === 252) { + return checkExpression(declaration.expression); + } + if (!pushTypeResolution(symbol, 0)) { + return errorType; + } + var type; + if (ts.isInJavaScriptFile(declaration) && + (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromJSPropertyAssignments(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + return type; } - function getAnnotatedAccessorType(accessor) { + function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { if (accessor.kind === 156) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); - return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + return getterTypeAnnotation; } else { var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + return setterTypeAnnotation; } } return undefined; } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } function getAnnotatedAccessorThisParameter(accessor) { var parameter = getAccessorThisParameter(accessor); return parameter && parameter.symbol; @@ -27649,56 +28087,56 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 156); - var setter = ts.getDeclarationOfKind(symbol, 157); - if (getter && ts.isInJavaScriptFile(getter)) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0)) { - return errorType; + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 156); + var setter = ts.getDeclarationOfKind(symbol, 157); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; } - var type = void 0; - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; + } + if (!pushTypeResolution(symbol, 0)) { + return errorType; + } + var type; + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; } else { - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); } else { - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } - type = anyType; } + type = anyType; } } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156); - error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); - } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 156); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } - links.type = type; } - return links.type; + return type; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -27706,6 +28144,7 @@ var ts; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); + var originalLinks = links; if (!links.type) { var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); if (jsDeclaration) { @@ -27723,32 +28162,45 @@ var ts; } } } - if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else if (symbol.valueDeclaration.kind === 202 || - symbol.valueDeclaration.kind === 187 && symbol.valueDeclaration.parent.kind === 202) { - links.type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - var type = createObjectType(16, symbol); - if (symbol.flags & 32) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 202 || + declaration.kind === 187 && declaration.parent.kind === 202) { + return getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (symbol.flags & 512 && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0)) { + return errorType; } - else { - links.type = strictNullChecks && symbol.flags & 16777216 ? getOptionalType(type) : type; + var exportEquals = getMergedSymbol(symbol.exports.get("export=")); + var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); } + return type_1; } } - return links.type; + var type = createObjectType(16, symbol); + if (symbol.flags & 32) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 ? getOptionalType(type) : type; + } } function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); } function getTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); @@ -27769,7 +28221,7 @@ var ts; } else { if (!pushTypeResolution(symbol, 0)) { - return errorType; + return links.type = errorType; } symbolInstantiationDepth++; var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); @@ -27866,8 +28318,8 @@ var ts; case 194: case 195: case 240: - case 300: case 301: + case 302: case 295: case 179: case 173: @@ -27923,15 +28375,18 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return false; + return isJavascriptConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + var isJavascript = ts.isInJavaScriptFile(location); + if (isJavascriptConstructorType(type) && !typeArgCount) { + return getSignaturesOfType(type, 0); + } + return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); @@ -28005,6 +28460,9 @@ var ts; else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; } + else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + } else { var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); if (!constructors.length) { @@ -28305,7 +28763,8 @@ var ts; return false; } function isThislessTypeParameter(node) { - return !node.constraint || isThislessType(node.constraint); + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); } function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); @@ -28373,6 +28832,11 @@ var ts; && ts.isEntityNameExpression(node.expression) && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 && + name.charCodeAt(1) === 95 && + name.charCodeAt(2) === 64; + } function hasLateBindableName(node) { var name = ts.getNameOfDeclaration(node); return !!name && isLateBindableName(name); @@ -28726,7 +29190,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_4 = function (i) { var t = type.types[i]; if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { var signatures = getSignaturesOfType(t, 1); @@ -28744,7 +29208,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_4(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -28834,7 +29298,7 @@ var ts; if (isMappedTypeWithKeyofConstraintDeclaration(type)) { for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), undefined, prop); + addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); } if (modifiersType.flags & 1 || getIndexInfoOfType(modifiersType, 0)) { addMemberForKeyType(stringType); @@ -28849,7 +29313,7 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - function addMemberForKeyType(t, _index, origin) { + function addMemberForKeyType(t) { var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); var propType = instantiateType(templateType, templateMapper); if (t.flags & 2240) { @@ -28863,9 +29327,9 @@ var ts; prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 ? getTypeWithFacts(propType, 131072) : propType; - if (origin) { - prop.syntheticOrigin = origin; - prop.declarations = origin.declarations; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; } prop.nameType = t; members.set(propName, prop); @@ -28893,7 +29357,7 @@ var ts; errorType); } function getConstraintDeclarationForMappedType(type) { - return type.declaration.typeParameter.constraint; + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); @@ -29009,11 +29473,7 @@ var ts; return obj.properties.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - if (expected && typeIsLiteralType(expected)) { - var actual = getTypeOfNode(property); - return !!actual && !isTypeIdenticalTo(actual, expected); - } - return false; + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -29108,20 +29568,12 @@ var ts; } return undefined; } - function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { + function getBaseConstraintOfType(type) { if (type.flags & (14745600 | 786432)) { var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - } - function getBaseConstraintOfType(type) { - var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); - if (!constraint && type.flags & 1048576) { - return keyofConstraintType; - } - return constraint; + return type.flags & 1048576 ? keyofConstraintType : undefined; } function getBaseConstraintOrType(type) { return getBaseConstraintOfType(type) || type; @@ -29130,23 +29582,24 @@ var ts; return getResolvedBaseConstraint(type) !== circularConstraintType; } function getResolvedBaseConstraint(type) { - var circular; - if (!type.resolvedBaseConstraint) { - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4)) { + return circularConstraintType; + } + var result = computeBaseConstraint(getSimplifiedType(t)); + if (!popTypeResolution()) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; } - return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (!pushTypeResolution(t, 4)) { - circular = true; - return undefined; - } - var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { - circular = true; - return undefined; - } - return result; + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { if (t.flags & 65536) { @@ -29159,8 +29612,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_3 = types_4[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_4[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -29237,6 +29690,7 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; + var indexTypes; var isUnion = containingType.flags & 262144; var excludeModifiers = isUnion ? 24 : 0; var commonFlags = isUnion ? 0 : 16777216; @@ -29261,14 +29715,21 @@ var ts; } } else if (isUnion) { - checkFlags |= 16; + var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1)) || getIndexInfoOfType(type, 0)); + if (index) { + checkFlags |= index.isReadonly ? 8 : 0; + indexTypes = ts.append(indexTypes, index.type); + } + else { + checkFlags |= 16; + } } } } if (!props) { return undefined; } - if (props.length === 1 && !(checkFlags & 16)) { + if (props.length === 1 && !(checkFlags & 16) && !indexTypes) { return props[0]; } var declarations; @@ -29300,6 +29761,7 @@ var ts; } propTypes.push(type); } + ts.addRange(propTypes, indexTypes); var result = createSymbol(4 | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && commonValueDeclaration) { @@ -29443,16 +29905,6 @@ var ts; var isBracketed = node.isBracketed, typeExpression = node.typeExpression; return isBracketed || !!typeExpression && typeExpression.type.kind === 286; } - function createTypePredicateFromTypePredicateNode(node) { - var parameterName = node.parameterName; - var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71) { - return createIdentifierTypePredicate(parameterName && parameterName.escapedText, parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); - } - else { - return createThisTypePredicate(type); - } - } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; } @@ -29549,9 +30001,8 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -29572,24 +30023,14 @@ var ts; parameters.push(syntheticArgsSymbol); return true; } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); - } - else if (classType) { - return classType; - } - var typeNode = ts.getEffectiveReturnTypeNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); - } - if (declaration.kind === 156 && !hasNonBindableDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); } function containsArgumentsReference(declaration) { var links = getNodeLinks(declaration); @@ -29666,52 +30107,105 @@ var ts; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJavaScriptFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type) : - noTypePredicate; + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 71) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3)) { return errorType; } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2) : + getReturnTypeFromAnnotation(signature.declaration) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + type = anyType; } signature.resolvedReturnType = type; } return signature.resolvedReturnType; } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 155) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 156 && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } function isResolvingReturnTypeOfSignature(signature) { return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3) >= 0; } function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1) || anyType; + return type && getIndexTypeOfType(type, 1); } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -29800,7 +30294,7 @@ var ts; } function getConstraintDeclaration(type) { var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148); - return decl && decl.constraint; + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { var inferences; @@ -29849,7 +30343,9 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 148).parent); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); } function getTypeListId(types) { var result = ""; @@ -30012,6 +30508,10 @@ var ts; if (referenceType || assignedType) { return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } + var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag && enumTag.typeExpression) { + return getTypeFromTypeNode(enumTag.typeExpression); + } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 | 64)) { @@ -30061,7 +30561,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152) && node.kind === 162; + return !!(node.flags & 2097152) && (node.kind === 162 || node.kind === 181); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -30146,7 +30646,7 @@ var ts; function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getWidenedType(checkExpression(node.exprName)); + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); } return links.resolvedType; } @@ -30261,6 +30761,9 @@ var ts; function createArrayType(elementType) { return createTypeFromGenericGlobalType(globalArrayType, [elementType]); } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -30352,6 +30855,14 @@ var ts; function containsType(types, type) { return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } function isEmptyIntersectionType(type) { var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { @@ -30494,7 +31005,7 @@ var ts; includes & 8192 ? includes & 134217728 ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, includes & 16749629 ? 0 : 67108864, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 16748579 ? 0 : 67108864, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -30598,26 +31109,52 @@ var ts; } } } - function intersectUnionsOfUnitTypes(types) { - var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 67108864) !== 0; }); - var unionType = types[unionIndex]; - var intersection = unionType.types; - var i = types.length - 1; - var _loop_6 = function () { + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 64 ? stringType : + type.flags & 128 ? numberType : + type.flags & 2048 ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return (t.flags & 67108864) !== 0; }); + var i = index + 1; + while (i < types.length) { var t = types[i]; if (t.flags & 67108864) { - intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } - i--; - }; - while (i > unionIndex) { - _loop_6(); + else { + i++; + } } - if (intersection === unionType.types) { + if (!unionTypes) { return false; } - types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 67108864); + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + types[index] = getUnionTypeFromSortedList(result, 67108864); return true; } function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -30647,7 +31184,7 @@ var ts; return typeSet[0]; } if (includes & 262144) { - if (includes & 67108864 && intersectUnionsOfUnitTypes(typeSet)) { + if (includes & 67108864 && intersectUnionsOfPrimitiveTypes(typeSet)) { return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); } var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144) !== 0; }); @@ -30753,6 +31290,24 @@ var ts; type.indexType = indexType; return type; } + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; + } + if (ts.getObjectFlags(type) & 16384) { + return true; + } + if (type.flags & 262144) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 524288) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 15794176) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 188 ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : @@ -30772,7 +31327,8 @@ var ts; getNodeLinks(accessNode).resolvedSymbol = prop; } } - return getTypeOfSymbol(prop); + var propType = getTypeOfSymbol(prop); + return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; } if (isTupleType(objectType)) { var restType = getRestTypeOfTupleType(objectType); @@ -30782,7 +31338,7 @@ var ts; } } if (!(indexType.flags & 24576) && isTypeAssignableToKind(indexType, 68 | 168 | 3072)) { - if (isTypeAny(objectType)) { + if (objectType.flags & (1 | 32768)) { return objectType; } var indexInfo = isTypeAssignableToKind(indexType, 168) && getIndexInfoOfType(objectType, 1) || @@ -30801,9 +31357,15 @@ var ts; if (indexType.flags & 32768) { return neverType; } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1)) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1)) { error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); } else { @@ -30821,6 +31383,9 @@ var ts; return anyType; } } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessNode) { var indexNode = accessNode.kind === 188 ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (64 | 128)) { @@ -30889,7 +31454,7 @@ var ts; return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 65536) { - var constraint = getConstraintFromTypeParameter(objectType); + var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); } @@ -31088,18 +31653,16 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var argumentType = getTypeFromTypeNode(node.argument); - var targetMeaning = node.isTypeOf ? 67216319 : 67901928; - var moduleName = argumentType.value; - var innerModuleSymbol = resolveExternalModule(node, moduleName, ts.Diagnostics.Cannot_find_module_0, node, false); + var targetMeaning = node.isTypeOf ? 67216319 : node.flags & 2097152 ? 67216319 | 67901928 : 67901928; + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var moduleSymbol_1 = resolveExternalModuleSymbol(innerModuleSymbol, false); + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); - var currentNamespace = moduleSymbol_1; + var currentNamespace = moduleSymbol; var current = void 0; while (current = nameStack.shift()) { var meaning = nameStack.length ? 1920 : targetMeaning; @@ -31115,14 +31678,14 @@ var ts; resolveImportSymbolType(node, links, currentNamespace, targetMeaning); } else { - if (moduleSymbol_1.flags & targetMeaning) { - resolveImportSymbolType(node, links, moduleSymbol_1, targetMeaning); + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { var errorMessage = targetMeaning === 67216319 ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; - error(node, errorMessage, moduleName); + error(node, errorMessage, node.argument.literal.text); links.resolvedSymbol = unknownSymbol; links.resolvedType = errorType; } @@ -31201,19 +31764,16 @@ var ts; } for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; - var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { skippedPrivateMembers.set(rightProp.escapedName, true); } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + else if (isSpreadableProperty(rightProp)) { members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { var leftProp = _c[_b]; - if (leftProp.flags & 65536 && !(leftProp.flags & 32768) - || skippedPrivateMembers.has(leftProp.escapedName) - || isClassMethod(leftProp)) { + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { continue; } if (members.has(leftProp.escapedName)) { @@ -31240,6 +31800,11 @@ var ts; spread.objectFlags |= objectFlags | (128 | 1024); return spread; } + function isSpreadableProperty(prop) { + return prop.flags & (8192 | 32768) + ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) + : !(prop.flags & 65536); + } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { return prop; @@ -31258,9 +31823,6 @@ var ts; } return index; } - function isClassMethod(prop) { - return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } function createLiteralType(flags, value, symbol) { var type = createType(flags); type.symbol = symbol; @@ -31414,7 +31976,7 @@ var ts; case 71: case 146: var symbol = getSymbolAtLocation(node); - return (symbol && getDeclaredTypeOfSymbol(symbol)); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: return errorType; } @@ -31567,7 +32129,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, true); - if (isJavaScriptConstructor(declaration_1)) { + if (isJavascriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -31629,7 +32191,11 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); + var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); } return t; }); @@ -31641,6 +32207,25 @@ var ts; function isMappableType(type) { return type.flags & (3 | 14745600 | 131072 | 524288); } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 ? 0 : + modifiers & 8 ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 && isOptional ? getTypeWithFacts(propType, 131072) : + propType; + } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64, type.symbol); if (type.objectFlags & 32) { @@ -31775,6 +32360,9 @@ var ts; return true; } } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { var body = node.body; return body.kind === 216 ? false : isContextSensitive(body); } @@ -31785,7 +32373,7 @@ var ts; function getTypeWithoutSignatures(type) { if (type.flags & 131072) { var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { + if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16, type.symbol); result.members = resolved.members; result.properties = resolved.properties; @@ -31893,8 +32481,8 @@ var ts; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } - if (!issuedElaboration && (ts.length(targetProp && targetProp.declarations) || ts.length(target.symbol && target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); } } reportedError = true; @@ -32033,9 +32621,9 @@ var ts; source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceRestTypeParameter = getRestTypeParameter(source); - var targetRestTypeParameter = sourceRestTypeParameter ? getRestTypeParameter(target) : undefined; - if (sourceRestTypeParameter && !(targetRestTypeParameter && sourceCount === targetCount)) { + var sourceGenericRestType = getGenericRestType(source); + var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; + if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { return 0; } var kind = target.declaration ? target.declaration.kind : 0; @@ -32060,8 +32648,8 @@ var ts; var paramCount = Math.max(sourceCount, targetCount); var lastIndex = paramCount - 1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceRestTypeParameter || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetRestTypeParameter || getTypeAtPosition(target, i); + var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); + var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && @@ -32078,11 +32666,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? + getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? + getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); @@ -32519,6 +33109,9 @@ var ts; return 0; } function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384) { + return false; + } if (maybeTypeOfKind(target, 131072) && !(ts.getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && @@ -32528,7 +33121,7 @@ var ts; if (discriminant) { return hasExcessProperties(source, discriminant, undefined, reportErrors); } - var _loop_7 = function (prop) { + var _loop_5 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { if (!errorNode) @@ -32561,9 +33154,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_7(prop); - if (typeof state_3 === "object") - return state_3.value; + var state_2 = _loop_5(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -32595,7 +33188,8 @@ var ts; } if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || - findMatchingTypeReferenceOrTypeAliasReference(source, target); + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], true); } return 0; @@ -32617,6 +33211,11 @@ var ts; }); } } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } function findMatchingDiscriminantType(source, target) { var match; var sourceProperties = getPropertiesOfObjectType(source); @@ -33139,8 +33738,12 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1; } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); + var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1) ? + 0 : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1) ? + 0 : kind); if (kind === 1 && sourceSignatures.length && targetSignatures.length) { if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { if (reportErrors) { @@ -33347,7 +33950,7 @@ var ts; return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 && !getConstraintFromTypeParameter(type); + return type.flags & 65536 && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -33563,6 +34166,9 @@ var ts; function isArrayType(type) { return !!(ts.getObjectFlags(type) & 4) && type.target === globalArrayType; } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4) && type.target === globalReadonlyArrayType; + } function isArrayLikeType(type) { return ts.getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || !(type.flags & 24576) && isTypeAssignableTo(type, anyReadonlyArrayType); @@ -33721,7 +34327,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags & ~33554432; - regularNew.objectFlags |= 128; + regularNew.objectFlags |= 128 | (ts.getObjectFlags(resolved) & 16384); type.regularType = regularNew; return regularNew; } @@ -33797,7 +34403,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(type, 0); var numberIndexInfo = getIndexInfoOfType(type, 1); - return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384); + return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, undefined); @@ -33914,13 +34522,13 @@ var ts; sourceHasRest ? targetCount : targetHasRest ? sourceCount : Math.min(sourceCount, targetCount); - var targetRestTypeVariable = getRestTypeParameter(target); - var paramCount = targetRestTypeVariable ? Math.min(targetCount - 1, maxCount) : maxCount; + var targetGenericRestType = getGenericRestType(target); + var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetRestTypeVariable) { - callback(getRestTypeAtPosition(source, paramCount), targetRestTypeVariable); + if (targetGenericRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -34020,6 +34628,18 @@ var ts; return undefined; } } + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var minLength = getMappedTypeModifiers(target) & 4 ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } var reversed = createObjectType(2048 | 16, undefined); reversed.source = source; reversed.mappedType = target; @@ -34507,7 +35127,7 @@ var ts; case 71: return ts.idText(name); case 147: - return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; case 9: case 8: return name.text; @@ -34530,8 +35150,9 @@ var ts; case 97: return target.kind === 97; case 187: - return target.kind === 187 && - source.name.escapedText === target.name.escapedText && + case 188: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); case 184: if (target.kind !== 187) @@ -34549,6 +35170,11 @@ var ts; } return false; } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } function containsMatchingReference(source, target) { while (source.kind === 187) { source = source.expression; @@ -34624,24 +35250,12 @@ var ts; } return flow.id; } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 262144)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { if (assignedType.flags & 32768) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); if (!(reducedType.flags & 32768)) { return reducedType; } @@ -35105,7 +35719,10 @@ var ts; } else if (flags & 2) { var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 187 && reference.kind !== 99) { + if (container && container !== flowContainer && + reference.kind !== 187 && + reference.kind !== 188 && + reference.kind !== 99) { flow = container.flowNode; continue; } @@ -35282,13 +35899,22 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 187 && - computedType.flags & 262144 && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(computedType, expr.name.escapedText); + if (!(computedType.flags & 262144) || + expr.kind !== 187 && expr.kind !== 188) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.escapedText; + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); @@ -35549,6 +36175,7 @@ var ts; case 99: case 97: case 187: + case 188: return narrowTypeByTruthiness(type, expr, assumeTrue); case 189: return narrowTypeByTypePredicate(type, expr, assumeTrue); @@ -35731,12 +36358,13 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728; while (flowContainer !== declarationContainer && (flowContainer.kind === 194 || flowContainer.kind === 195 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3) !== 0 || isInTypeQuery(node) || node.parent.kind === 255) || node.parent.kind === 211 || @@ -35859,13 +36487,13 @@ var ts; } function checkThisExpression(node) { var container = ts.getThisContainer(node, true); - var needToCaptureLexicalThis = false; + var capturedByArrowFunction = false; if (container.kind === 155) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } if (container.kind === 195) { container = ts.getThisContainer(container, false); - needToCaptureLexicalThis = (languageVersion < 2); + capturedByArrowFunction = true; } switch (container.kind) { case 242: @@ -35889,12 +36517,14 @@ var ts; error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } - if (needToCaptureLexicalThis) { + if (capturedByArrowFunction && languageVersion < 2) { captureLexicalThis(node, container); } var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + error(node, capturedByArrowFunction && container.kind === 277 ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); } return type || anyType; } @@ -35914,6 +36544,13 @@ var ts; return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); } } + else if ((container.kind === 194 || container.kind === 237) && + ts.getJSDocClassTag(container)) { + var classType = getJavascriptClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return getFlowTypeOfReference(node, thisType); @@ -36141,19 +36778,10 @@ var ts; } var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameter = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameter ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - if (funcHasRestParameter && indexOfParameter === len) { - return getRestTypeAtPosition(contextualSignature, indexOfParameter); - } + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); } } function getContextualTypeForInitializerExpression(node) { @@ -36229,10 +36857,9 @@ var ts; return false; } function getContextualReturnType(functionDecl) { - if (functionDecl.kind === 155 || - ts.getEffectiveReturnTypeNode(functionDecl) || - isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; } var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); if (signature && !isResolvingReturnTypeOfSignature(signature)) { @@ -36278,13 +36905,30 @@ var ts; case 0: return true; case 5: - return !binaryExpression.left.symbol; case 1: - case 2: + case 6: case 3: + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + if (ts.isInJavaScriptFile(decl)) { + return !!ts.getJSDocTypeTag(decl); + } + else if (ts.isIdentifier(binaryExpression.left.expression)) { + var id = binaryExpression.left.expression; + var parentSymbol = resolveName(id, id.escapedText, 67216319, undefined, id.escapedText, true); + return !ts.isFunctionSymbol(parentSymbol); + } + return true; + } case 4: - case 6: - return false; + case 2: + return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); default: return ts.Debug.assertNever(kind); } @@ -36633,16 +37277,11 @@ var ts; } function getContextualSignature(node) { ts.Debug.assert(node.kind !== 154 || ts.isObjectLiteralMethod(node)); - var type; - if (ts.isInJavaScriptFile(node)) { - var jsdoc = ts.getJSDocType(node); - if (jsdoc) { - type = getTypeFromTypeNode(jsdoc); - } - } - if (!type) { - type = getContextualTypeForFunctionLikeDeclaration(node); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; } + var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } @@ -36804,7 +37443,8 @@ var ts; var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 || contextualType.pattern.kind === 186); var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); - var isJSObjectLiteral = !contextualType && isInJSFile; + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -36828,6 +37468,9 @@ var ts; checkTypeAssignableTo(type, jsDocType, memberDecl); type = jsDocType; } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } } typeFlags |= type.flags; var nameType = computedNameType && computedNameType.flags & 2240 ? @@ -36926,12 +37569,15 @@ var ts; } return createObjectLiteralType(); function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432; result.flags |= 268435456 | freshObjectLiteralFlag | (typeFlags & 939524096); result.objectFlags |= 128; + if (isJSObjectLiteral) { + result.objectFlags |= 16384; + } if (patternWithComputedProperties) { result.objectFlags |= 512; } @@ -37240,7 +37886,7 @@ var ts; if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined, false); if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); @@ -37263,7 +37909,7 @@ var ts; var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, false); var result = void 0; var allMatchingAttributesType = void 0; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { @@ -37484,6 +38130,10 @@ var ts; } } } + else if (targetType.flags & 4194304) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } return false; } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { @@ -37522,9 +38172,6 @@ var ts; return errorType; } } - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 152; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } @@ -37538,18 +38185,14 @@ var ts; ts.getSpecialPropertyAssignmentKind(parent) === 3; } } - function checkPropertyAccessibility(node, left, type, prop) { + function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 187 || node.kind === 235 ? - node.name : - node.kind === 181 ? - node : - node.right; + var errorNode = node.kind === 146 ? node.right : node.kind === 181 ? node : node.name; if (ts.getCheckFlags(prop) & 256) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } - if (left.kind === 97) { + if (isSuper) { if (languageVersion < 2) { if (symbolHasNonMethodDeclaration(prop)) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); @@ -37579,7 +38222,7 @@ var ts; } return true; } - if (left.kind === 97) { + if (isSuper) { return true; } var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { @@ -37593,7 +38236,7 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536) ? getConstraintFromTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 65536) ? getConstraintOfTypeParameter(thisType) : thisType); } if (flags & 32) { return true; @@ -37612,10 +38255,7 @@ var ts; return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; } function symbolHasNonMethodDeclaration(symbol) { - return forEachProperty(symbol, function (prop) { - var propKind = getDeclarationKindFromSymbol(prop); - return propKind !== 154 && propKind !== 153; - }); + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192); }); } function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); @@ -37661,6 +38301,9 @@ var ts; if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0); if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, leftType.flags & 65536 && leftType.isThisType ? apparentType : leftType); } @@ -37675,7 +38318,7 @@ var ts; checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 97, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); @@ -37725,7 +38368,7 @@ var ts; diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializer(node) { @@ -37765,6 +38408,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; + var relatedInfo; if (containingType.flags & 262144 && !(containingType.flags & 32764)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; @@ -37774,42 +38418,61 @@ var ts; } } } - var promisedType = getPromisedTypeOfPromise(containingType); - if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - 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), suggestion); + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion_1 = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion_1 !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion_1); + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319); } function getSuggestionForNonexistentProperty(name, containingType) { - var suggestion = getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319); + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - return result && ts.symbolName(result); + return result; } - function getSuggestionForNonexistentModule(name, targetModule) { - var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475); + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); return suggestion && ts.symbolName(suggestion); } function getSpellingSuggestionForName(name, symbols, meaning) { @@ -37837,15 +38500,15 @@ var ts; function isValidPropertyAccess(node, propertyName) { switch (node.kind) { case 187: - return isValidPropertyAccessWithType(node, node.expression, propertyName, getWidenedType(checkExpression(node.expression))); + return isValidPropertyAccessWithType(node, node.expression.kind === 97, propertyName, getWidenedType(checkExpression(node.expression))); case 146: - return isValidPropertyAccessWithType(node, node.left, propertyName, getWidenedType(checkExpression(node.left))); + return isValidPropertyAccessWithType(node, false, propertyName, getWidenedType(checkExpression(node.left))); case 181: - return isValidPropertyAccessWithType(node, node, propertyName, getTypeFromTypeNode(node)); + return isValidPropertyAccessWithType(node, false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 181 ? node : node.expression, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 181 && node.expression.kind === 97, property.escapedName, type) && (!(property.flags & 8192) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -37865,13 +38528,13 @@ var ts; inferTypes(context.inferences, actualThisType, signatureThisType); return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); } - function isValidPropertyAccessWithType(node, left, propertyName, type) { + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { if (type === errorType || isTypeAny(type)) { return true; } var prop = getPropertyOfType(type, propertyName); - return prop ? checkPropertyAccessibility(node, left, type, prop) - : ts.isInJavaScriptFile(node) && (type.flags & 262144) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) + : ts.isInJavaScriptFile(node) && (type.flags & 262144) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } function getForInVariableSymbol(node) { var initializer = node.initializer; @@ -38034,7 +38697,6 @@ var ts; function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; - var typeArguments; var callIsIncomplete = false; var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { @@ -38042,7 +38704,6 @@ var ts; } if (node.kind === 191) { argCount = args.length; - typeArguments = node.typeArguments; if (node.template.kind === 204) { var lastSpan = ts.last(node.template.templateSpans); callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; @@ -38054,7 +38715,6 @@ var ts; } } else if (node.kind === 150) { - typeArguments = undefined; argCount = getEffectiveArgumentCount(node, undefined, signature); } else { @@ -38064,12 +38724,8 @@ var ts; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; callIsIncomplete = node.arguments.end === node.end; - typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } - if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { - return false; - } if (spreadArgIndex >= 0) { return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); } @@ -38141,8 +38797,8 @@ var ts; inferTypes(context.inferences, thisArgumentType, thisType); } var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var restTypeParameter = getRestTypeParameter(signature); - var argCount = restTypeParameter ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var genericRestType = getGenericRestType(signature); + var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); if (arg === undefined || arg.kind !== 208) { @@ -38155,9 +38811,9 @@ var ts; inferTypes(context.inferences, argType, paramType); } } - if (restTypeParameter) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, restTypeParameter, context); - inferTypes(context.inferences, spreadType, restTypeParameter); + if (genericRestType) { + var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); + inferTypes(context.inferences, spreadType, genericRestType); } if (excludeArgument) { for (var i = 0; i < argCount; i++) { @@ -38468,18 +39124,54 @@ var ts; return arg; } } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + min = Math.min(min, minCount); + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } var paramCount = min === max ? min : min + "-" + max; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 191; var isDecorator = node.kind === 150; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -38512,9 +39204,10 @@ var ts; } } var candidateForArgumentError; + var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 189 && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } @@ -38530,65 +39223,30 @@ var ts; } checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { - var min_1 = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; - min_1 = Math.min(min_1, getMinArgumentCount(sig)); - max = Math.max(max, getParameterCount(sig)); - } - var hasRestParameter_1 = ts.some(signatures, hasEffectiveRestParameter); - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - var paramCount = hasRestParameter_1 ? min_1 : - min_1 < max ? min_1 + "-" + max : - min_1; - var argCount = args.length; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - ts.Diagnostics.Expected_0_arguments_but_got_1; - diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + diagnostics.add(getArgumentArityError(node, signatures, args)); } else if (fallbackError) { diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } - if (!produceDiagnostics) { - ts.Debug.assert(candidates.length > 0); - var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); - var candidate = candidates[bestIndex]; - var typeParameters = candidate.typeParameters; - if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_1.length > typeParameters.length) { - typeArguments_1.pop(); - } - while (typeArguments_1.length < typeParameters.length) { - typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); - } - var instantiated = createSignatureInstantiation(candidate, typeArguments_1); - candidates[bestIndex] = instantiated; - return instantiated; - } - return candidate; - } - return resolveErrorCall(node); + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { @@ -38599,7 +39257,7 @@ var ts; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; @@ -38625,6 +39283,10 @@ var ts; } var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); + if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = candidate; + break; + } } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { candidateForArgumentError = candidate; @@ -38646,6 +39308,70 @@ var ts; return undefined; } } + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_6 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_6(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, undefined, thisParameter, parameters, getIntersectionType(candidates.map(getReturnTypeOfSignature)), undefined, minArgumentCount, hasRestParameter, candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments); + candidates[bestIndex] = instantiated; + return instantiated; + } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; var maxParams = -1; @@ -38662,18 +39388,21 @@ var ts; } return maxParamsIndex; } - function resolveCallExpression(node, candidatesOutArray) { + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.expression.kind === 97) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { - ts.forEach(node.arguments, checkExpresionNoReturn); + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); + } return anySignature; } if (superType !== errorType) { var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); } } return resolveUntypedCall(node); @@ -38703,13 +39432,17 @@ var ts; } return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 | 32768)) && isTypeAssignableTo(funcType, globalFunctionType); } - function resolveNewExpression(node, candidatesOutArray) { + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1) { var spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { @@ -38740,12 +39473,12 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray); + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); } var callSignatures = getSignaturesOfType(expressionType, 0); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } if (getThisTypeOfSignature(signature) === voidType) { @@ -38756,6 +39489,37 @@ var ts; invocationError(node, expressionType, 1); return resolveErrorCall(node); } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 524288) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 | 2)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } function isConstructorAccessible(node, signature) { if (!signature || !signature.declaration) { return true; @@ -38769,16 +39533,10 @@ var ts; var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); - if (containingClass) { + if (containingClass && modifiers & 16) { var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; } } if (modifiers & 8) { @@ -38808,7 +39566,7 @@ var ts; addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); if (apparentType === errorType) { @@ -38823,7 +39581,7 @@ var ts; invocationError(node, apparentType, 0); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { @@ -38842,7 +39600,7 @@ var ts; return ts.Debug.fail(); } } - function resolveDecorator(node, candidatesOutArray) { + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); if (apparentType === errorType) { @@ -38867,7 +39625,7 @@ var ts; invocationErrorRecovery(apparentType, 0, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { @@ -38876,29 +39634,29 @@ var ts; signature.parameters.length < getEffectiveArgumentCount(decorator, undefined, signature); }); } - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { ts.Debug.assert(!(elementType.flags & 262144)); var callSignatures = elementType && getSignaturesOfType(elementType, 0); if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); } return undefined; } - function resolveSignature(node, candidatesOutArray) { + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { case 189: - return resolveCallExpression(node, candidatesOutArray); + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); case 190: - return resolveNewExpression(node, candidatesOutArray); + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); case 191: - return resolveTaggedTemplateExpression(node, candidatesOutArray); + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); case 150: - return resolveDecorator(node, candidatesOutArray); + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); case 260: case 259: var exprTypes = checkExpression(node.tagName); return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); if (sfcResult && sfcResult !== unknownSignature) { return sfcResult; } @@ -38911,18 +39669,19 @@ var ts; } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } - function getResolvedSignature(node, candidatesOutArray) { + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } var links = getNodeLinks(node); var cached = links.resolvedSignature; if (cached && cached !== resolvingSignature && !candidatesOutArray) { return cached; } links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } - function isJavaScriptConstructor(node) { + function isJavascriptConstructor(node) { if (node && ts.isInJavaScriptFile(node)) { if (ts.getJSDocClassTag(node)) return true; @@ -38933,14 +39692,21 @@ var ts; } return false; } - function getJavaScriptClassType(symbol) { + function isJavascriptConstructorType(type) { + if (type.flags & 131072) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJavascriptClassType(symbol) { var inferred; - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -39003,7 +39769,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavaScriptClassType(funcSymbol); + var type = funcSymbol && getJavascriptClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -39026,7 +39792,8 @@ var ts; if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { - jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384; } } } @@ -39136,7 +39903,7 @@ var ts; if (produceDiagnostics && targetType !== errorType) { var widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); } } return targetType; @@ -39203,6 +39970,9 @@ var ts; return restParameter.escapedName; } function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); @@ -39213,22 +39983,19 @@ var ts; if (pos - paramCount < getLengthOfTupleType(restType)) { return restType.typeArguments[pos - paramCount]; } - var tupleRestType = getRestTypeOfTupleType(restType); - if (tupleRestType) { - return tupleRestType; - } + return getRestTypeOfTupleType(restType); } - return getIndexTypeOfType(restType, 1) || anyType; + return getIndexTypeOfType(restType, 1); } - return anyType; + return undefined; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); var hasRest = hasEffectiveRestParameter(source); if (hasRest && pos === paramCount - 1) { - var restTypeVariable = getRestTypeParameter(source); - if (restTypeVariable) { - return restTypeVariable; + var genericRestType = getGenericRestType(source); + if (genericRestType) { + return genericRestType; } } var start = hasRest ? Math.min(pos, paramCount - 1) : pos; @@ -39274,10 +40041,10 @@ var ts; } return signature.minArgumentCount; } - function getRestTypeParameter(signature) { + function getGenericRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 65536) { + if (restType.flags & 15794176) { return restType; } } @@ -39523,7 +40290,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -39543,7 +40310,7 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType && maybeTypeOfKind(returnType, 3 | 4096)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 4096)) { return; } if (func.kind === 153 || ts.nodeIsMissing(func.body) || func.body.kind !== 216 || !functionHasImplicitReturn(func)) { @@ -39575,6 +40342,15 @@ var ts; function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 || ts.isObjectLiteralMethod(node)); if (checkMode === 1 && isContextSensitive(node)) { + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); + return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + } return anyFunctionType; } var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); @@ -39601,7 +40377,7 @@ var ts; contextualSignature : instantiateSignature(contextualSignature, contextualMapper); assignContextualParameterTypes(signature, instantiatedContextualSignature); } - if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, checkMode); if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; @@ -39614,19 +40390,20 @@ var ts; } return type; } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3) === 2) ? + getAwaitedType(type) || errorType : type; + } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 154 || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - var returnOrPromisedType = returnTypeNode && - ((functionFlags & 3) === 2 ? - checkAsyncFunctionReturnType(node) : - getTypeFromTypeNode(returnTypeNode)); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1) === 0) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { - if (!returnTypeNode) { + if (!ts.getEffectiveReturnTypeNode(node)) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } if (node.body.kind === 216) { @@ -39669,7 +40446,7 @@ var ts; if (!(func && func.kind === 155)) { return true; } - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -39753,6 +40530,7 @@ var ts; } return numberType; case 51: + checkTruthinessExpression(node.operand); var facts = getTypeFacts(operandType) & (1048576 | 2097152); return facts === 1048576 ? falseType : facts === 2097152 ? trueType : @@ -39848,18 +40626,19 @@ var ts; } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType) { + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { var properties = node.properties; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 273 || property.kind === 274) { var name = property.name; if (name.kind === 147) { @@ -39868,19 +40647,9 @@ var ts; if (isComputedNonLiteralName(name)) { return undefined; } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || - getIndexTypeOfType(objectLiteralType, 0); + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { - if (property.kind === 274) { - return checkDestructuringAssignment(property, type); - } - else { - return checkDestructuringAssignment(property.initializer, type); - } + return checkDestructuringAssignment(property.kind === 274 ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); @@ -39904,6 +40673,23 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0); + } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 && compilerOptions.downlevelIteration) { @@ -39956,7 +40742,7 @@ var ts; } return undefined; } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; if (exprOrAssignment.kind === 274) { var prop = exprOrAssignment; @@ -39977,7 +40763,7 @@ var ts; target = target.left; } if (target.kind === 186) { - return checkObjectLiteralAssignment(target, sourceType); + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } if (target.kind === 185) { return checkArrayLiteralAssignment(target, sourceType, checkMode); @@ -40056,9 +40842,15 @@ var ts; function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; if (operator === 58 && (left.kind === 186 || left.kind === 185)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99); + } + var leftType; + if (operator === 53 || operator === 54) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); } - var leftType = checkExpression(left, checkMode); var rightType = checkExpression(right, checkMode); switch (operator) { case 39: @@ -40171,7 +40963,7 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2) : leftType; case 58: - var special = ts.getSpecialPropertyAssignmentKind(left.parent); + var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0; checkSpecialAssignment(special, right); if (isJSSpecialPropertyAssignment(special)) { return leftType; @@ -40243,8 +41035,9 @@ var ts; } function isJSSpecialPropertyAssignment(special) { switch (special) { - case 1: case 2: + return true; + case 1: case 5: case 6: case 3: @@ -40320,15 +41113,15 @@ var ts; } var isAsync = (functionFlags & 2) !== 0; var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); - var returnType = ts.getEffectiveReturnTypeNode(func); + var returnType = getReturnTypeFromAnnotation(func); if (returnType) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); } return anyType; } function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); + checkTruthinessExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2); @@ -40336,7 +41129,7 @@ var ts; function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072)) { - error(templateSpan.expression, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1, typeToString(esSymbolType), typeToString(stringType)); + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; @@ -40473,9 +41266,6 @@ var ts; node.contextualType = saveContextualType; return type; } - function checkExpresionNoReturn(node) { - checkExpression(node); - } function checkExpression(node, checkMode) { var type; if (node.kind === 146) { @@ -40604,7 +41394,7 @@ var ts; checkSourceElement(node.default); var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } if (!hasNonCircularTypeParameterDefault(typeParameter)) { error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); @@ -40640,22 +41430,14 @@ var ts; if (func.kind === 155 || func.kind === 159 || func.kind === 164) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } + if (func.kind === 195) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } } if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 && param.name.escapedText === parameter.escapedText) { - return i; - } - } - } - return -1; - } function checkTypePredicate(node) { var parent = getTypePredicateParent(node); if (!parent) { @@ -40785,7 +41567,7 @@ var ts; } } else if ((functionFlags_1 & 3) === 2) { - checkAsyncFunctionReturnType(node); + checkAsyncFunctionReturnType(node, returnTypeNode); } } if (node.kind !== 160 && node.kind !== 287) { @@ -41186,7 +41968,10 @@ var ts; } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, keyofConstraintType, node.typeParameter.constraint); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); } function checkTypeOperator(node) { checkGrammarTypeOperatorNode(node); @@ -41200,6 +41985,7 @@ var ts; grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); } function checkImportType(node) { checkSourceElement(node.argument); @@ -41444,7 +42230,7 @@ var ts; switch (d.kind) { case 239: case 240: - case 301: + case 302: case 295: return 2; case 242: @@ -41566,28 +42352,27 @@ var ts; } return typeAsAwaitable.awaitedTypeOfType = type; } - function checkAsyncFunctionReturnType(node) { - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + function checkAsyncFunctionReturnType(node, returnTypeNode) { var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2) { if (returnType === errorType) { - return errorType; + return; } var globalPromiseType = getGlobalPromiseType(true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return errorType; + return; } } else { markTypeNodeAsReferenced(returnTypeNode); if (returnType === errorType) { - return errorType; + return; } var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === undefined) { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return errorType; + return; } var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319, true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; @@ -41598,24 +42383,24 @@ var ts; else { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); } - return errorType; + return; } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(true); if (globalPromiseConstructorLikeType === emptyObjectType) { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return errorType; + return; } var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } } - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } function checkDecorator(node) { var signature = getResolvedSignature(node); @@ -41745,9 +42530,13 @@ var ts; } } break; - case 154: case 156: case 157: + var otherKind = node.kind === 156 ? 157 : 156; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 154: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); @@ -41786,6 +42575,13 @@ var ts; } checkSourceElement(node.typeExpression); } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } @@ -41861,14 +42657,11 @@ var ts; } var body = node.kind === 153 ? undefined : node.body; checkSourceElement(body); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if ((functionFlags & 1) === 0) { - var returnOrPromisedType = returnTypeNode && (functionFlags & 2 - ? checkAsyncFunctionReturnType(node) - : getTypeFromTypeNode(returnTypeNode)); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } - if (produceDiagnostics && !returnTypeNode) { + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { reportImplicitAnyError(node, anyType); } @@ -41876,6 +42669,12 @@ var ts; getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } + if (ts.isInJavaScriptFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } } function registerForUnusedIdentifiersCheck(node) { if (produceDiagnostics) { @@ -41927,6 +42726,7 @@ var ts; case 163: case 164: case 240: + case 174: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -41937,7 +42737,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0, ts.createDiagnosticForNode(node, message, name)); + addDiagnostic(declaration, 0, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95; @@ -41956,14 +42756,14 @@ var ts; } var symbol = getSymbolOfNode(member); if (!symbol.isReferenced && ts.hasModifier(member, 8)) { - addDiagnostic(0, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + addDiagnostic(member, 0, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; case 155: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - addDiagnostic(0, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + addDiagnostic(parameter, 0, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } } break; @@ -41977,16 +42777,43 @@ var ts; } } function checkUnusedTypeParameters(node, addDiagnostic) { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304) && ts.last(getSymbolOfNode(node).declarations) === node) { + if (node.flags & 4194304 || node.kind !== 174 && ts.last(getSymbolOfNode(node).declarations) !== node) + return; + if (node.kind === 174) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + else { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; - if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144) && !isIdentifierThatStartsWithUnderscore(typeParameter.name)) { - addDiagnostic(1, ts.createDiagnosticForNode(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol))); + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 174 && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + ? ts.rangeOfNode(parent) + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } function addToGroup(map, key, value, getKey) { var keyString = String(getKey(key)); var group = map.get(keyString); @@ -42033,7 +42860,7 @@ var ts; var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); if (parameter && name) { if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - addDiagnostic(1, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + addDiagnostic(parameter, 1, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { @@ -42050,7 +42877,7 @@ var ts; (importClause.namedBindings.kind === 249 ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { - addDiagnostic(0, unuseds.length === 1 + addDiagnostic(importDecl, 0, unuseds.length === 1 ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); } @@ -42069,29 +42896,29 @@ var ts; addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - addDiagnostic(kind, bindingElements.length === 1 - ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); } } else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; - addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); } } }); unusedVariables.forEach(function (_a) { var declarationList = _a[0], declarations = _a[1]; if (declarationList.declarations.length === declarations.length) { - addDiagnostic(0, declarations.length === 1 + addDiagnostic(declarationList, 0, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) : ts.createDiagnosticForNode(declarationList.parent.kind === 217 ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var decl = declarations_5[_i]; - addDiagnostic(0, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + addDiagnostic(decl, 0, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); } } }); @@ -42327,10 +43154,13 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, undefined, false); - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); + markPropertyAsReferenced(property, undefined, false); + if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + checkPropertyAccessibility(parent, parent.initializer.kind === 97, parentType, property); + } } } } @@ -42438,7 +43268,7 @@ var ts; } function checkIfStatement(node) { checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); if (node.thenStatement.kind === 218) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); @@ -42448,13 +43278,20 @@ var ts; function checkDoStatement(node) { checkGrammarStatementInAmbientContext(node); checkSourceElement(node.statement); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); } function checkWhileStatement(node) { checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.statement); } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 4096) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { if (node.initializer && node.initializer.kind === 236) { @@ -42470,7 +43307,7 @@ var ts; } } if (node.condition) - checkExpression(node.condition); + checkTruthinessExpression(node.condition); if (node.incrementor) checkExpression(node.incrementor); checkSourceElement(node.statement); @@ -42742,10 +43579,6 @@ var ts; if (!checkGrammarStatementInAmbientContext(node)) checkGrammarBreakOrContinueStatement(node); } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 156 - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 157)) !== undefined; - } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 ? getPromisedTypeOfPromise(returnType) @@ -42780,7 +43613,7 @@ var ts; error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + else if (getReturnTypeFromAnnotation(func)) { if (functionFlags & 2) { var promisedType = getPromisedTypeOfPromise(returnType); var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -43047,8 +43880,9 @@ var ts; if (source.name.escapedText !== target.symbol.escapedName) { return false; } - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); if (sourceConstraint) { if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { return false; @@ -43137,7 +43971,7 @@ var ts; } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 2162688)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -43179,7 +44013,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_7 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -43197,7 +44031,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_7(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -43868,9 +44702,9 @@ var ts; } } else { - var moduleSymbol_2 = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol_2 && hasExportAssignmentSymbol(moduleSymbol_2)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol_2)); + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + 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 && moduleKind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768); @@ -43954,9 +44788,9 @@ var ts; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } - var exports_2 = getExportsOfModule(moduleSymbol); - if (exports_2) { - exports_2.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -44049,6 +44883,8 @@ var ts; case 169: case 170: return checkSourceElement(node.type); + case 176: + return checkThisType(node); case 177: return checkTypeOperator(node); case 173: @@ -44059,12 +44895,14 @@ var ts; return checkImportType(node); case 293: return checkJSDocAugmentsTag(node); - case 301: + case 302: case 295: return checkJSDocTypeAliasTag(node); - case 299: + case 301: + return checkJSDocTemplateTag(node); + case 300: return checkJSDocTypeTag(node); - case 296: + case 297: return checkJSDocParameterTag(node); case 287: checkSignatureDeclaration(node); @@ -44256,7 +45094,7 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + if (ts.skipTypeChecking(node, compilerOptions)) { return; } checkGrammarSourceFile(node); @@ -44269,8 +45107,8 @@ var ts; registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { - if (unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { diagnostics.add(diag); } }); @@ -44335,6 +45173,7 @@ var ts; var symbols = ts.createSymbolTable(); var isStatic = false; populateSymbols(); + symbols.delete("this"); return symbolsToArray(symbols); function populateSymbols() { while (location) { @@ -44533,10 +45372,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 296) { + if (entityName.parent.kind === 297) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 && entityName.parent.parent.kind === 300) { + if (entityName.parent.kind === 148 && entityName.parent.parent.kind === 301) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -44601,7 +45440,7 @@ var ts; grandParent.kind === 182 && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; } @@ -44675,7 +45514,7 @@ var ts; } if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { var containingClass = ts.getContainingClass(node); var classType = getTypeOfNode(containingClass); typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); @@ -44688,8 +45527,8 @@ var ts; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { var classNode = ts.getContainingClass(node); var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } if (isTypeDeclaration(node)) { var symbol = getSymbolOfNode(node); @@ -44697,7 +45536,7 @@ var ts; } if (isTypeDeclarationName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } if (ts.isDeclaration(node)) { var symbol = getSymbolOfNode(node); @@ -44705,10 +45544,10 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); + return symbol ? getTypeOfSymbol(symbol) : errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, true); + return getTypeForVariableLikeDeclaration(node.parent, true) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -45229,7 +46068,8 @@ var ts; setAccessor: setAccessor, getAccessor: getAccessor }; - } + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, undefined); } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 && node.parent.parent && node.parent.parent.kind === 271; @@ -46255,9 +47095,6 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - if (node.name.kind === 183 || node.name.kind === 182) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (node.propertyName) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); } @@ -46501,9 +47338,9 @@ var ts; return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } if (node.parent.kind === 216 || node.parent.kind === 243 || node.parent.kind === 277) { - var links_1 = getNodeLinks(node.parent); - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + var links_2 = getNodeLinks(node.parent); + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); } } else { @@ -47598,19 +48435,7 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - 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; - } + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters @@ -47722,17 +48547,7 @@ var ts; return node; } ts.createConditional = createConditional; - 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]; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue @@ -48529,7 +49344,7 @@ var ts; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(259); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -48545,7 +49360,7 @@ var ts; function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(260); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -48826,28 +49641,28 @@ var ts; } ts.getMutableClone = getMutableClone; function createNotEmittedStatement(original) { - var node = createSynthesizedNode(304); + var node = createSynthesizedNode(305); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(308); + var node = createSynthesizedNode(309); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(307); + var node = createSynthesizedNode(308); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(305); + var node = createSynthesizedNode(306); node.expression = expression; node.original = original; setTextRange(node, original); @@ -48863,7 +49678,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 306) { + if (node.kind === 307) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { @@ -48873,7 +49688,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(306); + var node = createSynthesizedNode(307); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -49778,6 +50593,9 @@ var ts; var binaryOperatorPrecedence = ts.getOperatorPrecedence(202, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(202, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 195 && binaryOperatorPrecedence > 4) { + return true; + } var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1: @@ -49855,11 +50673,15 @@ var ts; ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; function parenthesizeDefaultExpression(e) { var check = ts.skipPartiallyEmittedExpressions(e); - return check.kind === 207 || - check.kind === 194 || - isCommaSequence(check) - ? ts.createParen(e) - : e; + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, false).kind) { + case 207: + case 194: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; } ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; function parenthesizeForNew(expression) { @@ -49994,6 +50816,9 @@ var ts; case 203: node = node.condition; continue; + case 191: + node = node.tag; + continue; case 189: if (stopAtCallExpressions) { return node; @@ -50002,7 +50827,7 @@ var ts; case 188: case 187: case 211: - case 305: + case 306: node = node.expression; continue; } @@ -50018,7 +50843,7 @@ var ts; ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { return node.kind === 202 && node.operatorToken.kind === 26 || - node.kind === 306; + node.kind === 307; } ts.isCommaSequence = isCommaSequence; function isOuterExpression(node, kinds) { @@ -50030,7 +50855,7 @@ var ts; case 210: case 211: return (kinds & 2) !== 0; - case 305: + case 306: return (kinds & 4) !== 0; } return false; @@ -50067,7 +50892,7 @@ var ts; case 192: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 210: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 211: return ts.updateNonNullExpression(outerExpression, expression); - case 305: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 306: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } function isIgnorableParen(node) { @@ -50234,7 +51059,7 @@ var ts; case 184: if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -50242,7 +51067,7 @@ var ts; case 273: if (bindingElement.name) { var propertyName = bindingElement.name; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -50252,13 +51077,18 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) ? target.expression : target; } ts.Debug.fail("Invalid property name for binding element."); } ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 + || kind === 8; + } function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { case 182: @@ -50697,9 +51527,9 @@ var ts; return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); case 277: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 305: - return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); case 306: + return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); + case 307: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -50737,7 +51567,7 @@ var ts; case 218: case 208: case 234: - case 304: + case 305: break; case 146: result = reduceNode(node.left, cbNode, result); @@ -51100,10 +51930,10 @@ var ts; case 277: result = reduceNodes(node.statements, cbNodes, result); break; - case 305: + case 306: result = reduceNode(node.expression, cbNode, result); break; - case 306: + case 307: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -51117,8 +51947,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) - : ts.prependStatements(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function liftToBlock(nodes) { @@ -51264,7 +52094,7 @@ var ts; function decode(host, mapPath, map, program, fallbackCache) { if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot || currentDirectory; + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; var decodedMappings; var generatedOrderedMappings; var sourceOrderedMappings; @@ -51296,9 +52126,9 @@ var ts; return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; } function getSourceFileLike(fileName, location) { - var file = program && program.getSourceFile(fileName); - if (!file) { - var path = ts.toPath(fileName, location, host.getCanonicalFileName); + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + var file = program && program.getSourceFile(path); + if (!file || file.resolvedPath !== path) { return fallbackCache.get(path); } return file; @@ -51967,7 +52797,7 @@ var ts; var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), false, propertyName); return ts.createElementAccess(value, argumentExpression); } - else if (ts.isStringOrNumericLiteral(propertyName)) { + else if (ts.isStringOrNumericLiteralLike(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); @@ -52403,7 +53233,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependStatements(statements, context.endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ @@ -52589,6 +53419,7 @@ var ts; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); statements.push(statement); } } @@ -52600,6 +53431,7 @@ var ts; ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); expressions.push(expression); } return expressions; @@ -52842,14 +53674,19 @@ var ts; } return false; } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } function serializeTypeOfNode(node) { switch (node.kind) { case 152: case 149: - case 156: return serializeTypeNode(node.type); case 157: - return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 156: + return serializeTypeNode(getAccessorTypeNode(node)); case 238: case 207: case 154: @@ -52998,11 +53835,11 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: - var serialized = serializeEntityNameAsExpression(node.typeName, true); + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName, false); + return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); case ts.TypeReferenceSerializationKind.BooleanType: @@ -53027,34 +53864,35 @@ var ts; return ts.Debug.assertNever(kind); } } - function serializeEntityNameAsExpression(node, useFallback) { + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 71) { + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 71) { + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } + function serializeEntityNameAsExpression(node) { switch (node.kind) { case 71: var name = ts.getMutableClone(node); name.flags &= ~8; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); - if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); - } return name; case 146: - return serializeQualifiedNameAsExpression(node, useFallback); + return serializeQualifiedNameAsExpression(node); } } - function serializeQualifiedNameAsExpression(node, useFallback) { - var left; - if (node.left.kind === 71) { - left = serializeEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, true)), temp); - } - else { - left = serializeEntityNameAsExpression(node.left, false); - } - return ts.createPropertyAccess(left, node.right); + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); } function getGlobalSymbolNameWithFallback() { return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object")); @@ -53264,7 +54102,8 @@ var ts; } var statements = []; var emitFlags = 2; - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512; } @@ -53281,8 +54120,12 @@ var ts; } var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); + if (varAdded) { + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } ts.setTextRange(enumStatement, node); - ts.setEmitFlags(enumStatement, emitFlags); + ts.addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); statements.push(ts.createEndOfDeclarationMarker(node)); return statements; @@ -53293,7 +54136,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); @@ -53366,7 +54209,7 @@ var ts; ts.setSourceMapRange(statement, node); } ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 | 4194304); + ts.addEmitFlags(statement, 1024 | 4194304); statements.push(statement); return true; } @@ -53385,7 +54228,8 @@ var ts; enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 2; - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512; } @@ -53402,8 +54246,12 @@ var ts; } var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } ts.setTextRange(moduleStatement, node); - ts.setEmitFlags(moduleStatement, emitFlags); + ts.addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); statements.push(ts.createEndOfDeclarationMarker(node)); return statements; @@ -53438,7 +54286,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -54005,7 +54853,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); if (languageVersion >= 2) { @@ -54520,7 +55368,7 @@ var ts; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { @@ -54546,7 +55394,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, true); - ts.prependStatements(statements, leadingStatements); + ts.addStatementsAfterPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -55411,7 +56259,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0, 0); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -55581,7 +56429,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); ts.setEmitFlags(block, 1536); return block; @@ -55644,7 +56492,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, false); } @@ -55711,7 +56559,7 @@ var ts; statements.push(returnStatement); return 2; } - captureThisForNode(statements, ctor, superCallExpression || createActualThis(), firstStatement); + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); if (superCallExpression) { return 1; } @@ -55809,13 +56657,12 @@ var ts; captureThisForNode(statements, node, ts.createThis()); } } - function captureThisForNode(statements, node, initializer, originalStatement) { + function captureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), undefined, initializer) ])); ts.setEmitFlags(captureThisStatement, 1536 | 1048576); - ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); } @@ -56044,7 +56891,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependStatements(statements, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, false); if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { multiLine = true; @@ -56210,7 +57057,7 @@ var ts; var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); return ts.isIterationStatement(statement, false) ? visitIterationStatement(statement, node) - : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement), node, convertedLoopState && resetLabel); + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { @@ -56447,7 +57294,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1, statements_4); } - ts.prependStatements(statements_4, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, true); } if (ts.isBlock(loopBody)) { @@ -57441,7 +58288,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); inGeneratorFunctionBody = savedInGeneratorFunctionBody; inStatementContainingYield = savedInStatementContainingYield; @@ -58909,7 +59756,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, false); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); @@ -59024,7 +59871,7 @@ var ts; } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); @@ -59069,9 +59916,9 @@ var ts; return visitFunctionDeclaration(node); case 238: return visitClassDeclaration(node); - case 307: - return visitMergeDeclarationMarker(node); case 308: + return visitMergeDeclarationMarker(node); + case 309: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -59232,7 +60079,7 @@ var ts; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { - return ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); } else { var variables = []; @@ -59245,12 +60092,12 @@ var ts; variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); } } - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 ? 2 : 0)), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 ? 2 : 0)), node), node)); } } else if (namespaceDeclaration && ts.isDefaultImport(node)) { statements = ts.append(statements, ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node)), node) + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node)), node), node) ], languageVersion >= 2 ? 2 : 0))); } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -59275,17 +60122,17 @@ var ts; var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); } else { - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), undefined, createRequireCall(node)) - ], languageVersion >= 2 ? 2 : 0)), node)); + ], languageVersion >= 2 ? 2 : 0)), node), node)); } } else { if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); } } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -59305,19 +60152,19 @@ var ts; if (node.exportClause) { var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(generatedName, undefined, createRequireCall(node)) - ])), node)); + ])), node), node)); } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); } return ts.singleOrMany(statements); } else { - return ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); } } function visitExportAssignment(node) { @@ -59391,7 +60238,7 @@ var ts; statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); } if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); } } else { @@ -59828,7 +60675,7 @@ var ts; ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); ts.addRange(statements, hoistedStatements); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -60275,9 +61122,9 @@ var ts; return visitCatchClause(node); case 216: return visitBlock(node); - case 307: - return visitMergeDeclarationMarker(node); case 308: + return visitMergeDeclarationMarker(node); + case 309: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -61066,7 +61913,8 @@ var ts; 4096 | 8 | 524288 | - 4; + 4 | + 1; function transformDeclarations(context) { var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; var getSymbolAccessibilityDiagnostic = throwDiagnostic; @@ -61080,6 +61928,7 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, @@ -61088,6 +61937,7 @@ var ts; reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode }; var errorNameNode; var currentSourceFile; @@ -61141,6 +61991,11 @@ var ts; } } } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } function trackSymbol(symbol, enclosingDeclaration, meaning) { if (symbol.flags & 262144) return; @@ -61168,7 +62023,7 @@ var ts; } if (node.kind === 278) { isBundledEmit = true; - var refs_1 = ts.createMap(); + refs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) @@ -61182,7 +62037,7 @@ var ts; getSymbolAccessibilityDiagnostic = throwDiagnostic; needsScopeFixMarker = false; resultHasScopeMarker = false; - collectReferences(sourceFile, refs_1); + collectReferences(sourceFile, refs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; needsDeclare = false; @@ -61203,7 +62058,7 @@ var ts; bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); - refs_1.forEach(referenceVisitor_1); + refs.forEach(referenceVisitor_1); return bundle; } needsDeclare = true; @@ -61230,6 +62085,7 @@ var ts; combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); } var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; function getFileReferencesForUsedTypeReferences() { return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; @@ -61437,10 +62293,18 @@ var ts; if (!input) return undefined; resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 && parent.kind !== 181); - if (input.kind === 9 && isBundledEmit) { - var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); - if (newName) { - return ts.createLiteral(newName); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } } } return input; @@ -61903,6 +62767,15 @@ var ts; } return false; } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } function ensureModifiers(node, privateDeclaration) { var currentFlags = ts.getModifierFlags(node); var newFlags = ensureModifierFlags(node, privateDeclaration); @@ -61916,7 +62789,7 @@ var ts; var additions = (needsDeclare && !isAlwaysType(node)) ? 2 : 0; var parentIsFile = node.parent.kind === 277; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { - mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) ? 0 : 1) | 512 | 2); + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1) | 2); additions = 0; } return maskModifierFlags(node, mask, additions); @@ -61934,7 +62807,7 @@ var ts; var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_8 = function (range) { if (range.kind === 3) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -61948,7 +62821,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_8(range); } } return prop; @@ -61973,6 +62846,9 @@ var ts; if (modifierMask === void 0) { modifierMask = 3071 ^ 4; } if (modifierAdditions === void 0) { modifierAdditions = 0; } var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 && !(flags & 1)) { + flags ^= 1; + } if (flags & 512 && flags & 2) { flags ^= 2; } @@ -62084,7 +62960,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(309); + var enabledSyntaxKindFeatures = new Array(310); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -62350,7 +63226,7 @@ var ts; if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); if (sourceFileOrBundle.kind === 277) { - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); @@ -62513,7 +63389,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 304 + if (node.kind !== 305 && (emitFlags & 16) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -62530,7 +63406,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 304 + if (node.kind !== 305 && (emitFlags & 32) === 0 && end >= 0) { emitPos(end); @@ -62675,7 +63551,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 304; + var isEmittedNode = node.kind !== 305; var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; if (!skipLeadingComments) { @@ -62684,10 +63560,10 @@ var ts; var savedContainerPos = containerPos; var savedContainerEnd = containerEnd; var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments) { + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512) !== 0)) { containerPos = pos; } - if (!skipTrailingComments) { + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024) !== 0)) { containerEnd = end; if (node.kind === 236) { declarationListContainerEnd = end; @@ -63001,16 +63877,16 @@ var ts; if (sourceFile.kind === 278) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); var isJs = ts.isSourceFileJavaScript(sourceFile); - var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } @@ -63058,6 +63934,7 @@ var ts; }); var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; + var exportedModulesFromDeclarationEmit; ts.performance.mark("beforePrint"); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); @@ -63066,6 +63943,7 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -63115,7 +63993,7 @@ var ts; var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; - if (emitOnlyDtsFiles && !compilerOptions.declaration) { + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { nonJsFiles.forEach(collectLinkedAliases); } var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), false); @@ -63139,6 +64017,10 @@ var ts; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], undefined, declarationPrinter, declarationSourceMap); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } } declarationTransform.dispose(); } @@ -63738,9 +64620,9 @@ var ts; return emitJsxSelfClosingElement(node); case 262: return emitJsxFragment(node); - case 305: - return emitPartiallyEmittedExpression(node); case 306: + return emitPartiallyEmittedExpression(node); + case 307: return emitCommaList(node); } } @@ -66208,7 +67090,7 @@ var ts; case WatchLogLevel.TriggerOnly: return createFileWatcherWithTriggerLogging; case WatchLogLevel.Verbose: - return createFileWatcherWithLogging; + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; } } function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { @@ -66221,9 +67103,27 @@ var ts; } }; } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { return addWatch(host, file, function (fileName, cbOptional) { - var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); log(triggerredInfo); var start = ts.timestamp(); cb(fileName, cbOptional, passThrough); @@ -66343,7 +67243,7 @@ var ts; } } ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); + var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -66669,6 +67569,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json"]) : undefined; var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; var _referencesArrayLiteralSyntax; @@ -66700,7 +67601,7 @@ var ts; } var packageIdToSourceFile = ts.createMap(); var sourceFileToPackageName = ts.createMap(); - var redirectTargetsSet = ts.createMap(); + var redirectTargetsMap = ts.createMultiMap(); var filesByName = ts.createMap(); var missingFilePaths; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; @@ -66793,7 +67694,7 @@ var ts; getSourceFileFromReference: getSourceFileFromReference, getLibFileFromReference: getLibFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsMap: redirectTargetsMap, isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -67013,7 +67914,7 @@ var ts; fileChanged = false; newSourceFile = oldSourceFile; } - else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { if (newSourceFile !== oldSourceFile) { return oldProgram.structureIsReused = 0; } @@ -67119,7 +68020,7 @@ var ts; resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; - redirectTargetsSet = oldProgram.redirectTargetsSet; + redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { @@ -67282,7 +68183,7 @@ var ts; } function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { - if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { + if (ts.skipTypeChecking(sourceFile, options)) { return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); @@ -67634,7 +68535,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -67708,8 +68609,16 @@ var ts; function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { if (filesByName.has(path)) { var file_1 = filesByName.get(path); - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } } if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { sourceFilesFoundSearchingNodeModules.set(file_1.path, false); @@ -67751,7 +68660,7 @@ var ts; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); - redirectTargetsSet.set(fileFromPackageId.path, true); + redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); @@ -67956,7 +68865,7 @@ var ts; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); allFilesBelongToPath = false; } } @@ -67971,6 +68880,7 @@ var ts; if (sourceFile === undefined) { return undefined; } + sourceFile.path = toPath(refPath); var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } @@ -67984,7 +68894,7 @@ var ts; ts.getDirectoryPath(proj.options.configFilePath); } function verifyCompilerOptions() { - if (options.strictPropertyInitialization && !options.strictNullChecks) { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { @@ -68043,14 +68953,14 @@ var ts; if (options.composite && rootNames.length < files.length) { var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_10 = function (file) { + var _loop_9 = function (file) { if (normalizedRootNames.every(function (r) { return r !== file; })) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); } }; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var file = sourceFiles_4[_i]; - _loop_10(file); + _loop_9(file); } } if (options.paths) { @@ -68106,7 +69016,7 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } - if (options.declarationMap && !options.declaration) { + if (options.declarationMap && !ts.getEmitDeclarations(options)) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); } if (options.lib && options.noLib) { @@ -68145,6 +69055,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } + else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + } } if (options.outDir || options.sourceRoot || @@ -68266,12 +69179,12 @@ var ts; } function createDiagnosticForReference(index, message, arg0, arg1) { var referencesSyntax = getProjectReferencesSyntax(); - if (referencesSyntax) { - if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { - return; - } + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); @@ -68321,13 +69234,6 @@ var ts; } return !!props.length; } - function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { - if (arrayLiteral.elements.length <= index) { - return false; - } - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); - return false; - } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -68385,7 +69291,6 @@ var ts; switch (extension) { case ".ts": case ".d.ts": - case ".json": return undefined; case ".tsx": return needJsx(); @@ -68393,6 +69298,8 @@ var ts; return needJsx() || needAllowJs(); case ".js": return needAllowJs(); + case ".json": + return needResolveJsonModule(); } function needJsx() { return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; @@ -68400,6 +69307,9 @@ var ts; function needAllowJs() { return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } } ts.getResolutionDiagnostic = getResolutionDiagnostic; function getModuleNames(_a) { @@ -68419,7 +69329,7 @@ var ts; function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -68429,18 +69339,25 @@ var ts; (function (ts) { var BuilderState; (function (BuilderState) { + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.path; + } + } + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } function getReferencedFiles(program, sourceFile, getCanonicalFileName) { var referencedFiles; if (sourceFile.imports && sourceFile.imports.length > 0) { var checker = program.getTypeChecker(); for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); } } } @@ -68477,6 +69394,7 @@ var ts; function create(newProgram, getCanonicalFileName, oldState) { var fileInfos = ts.createMap(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; var hasCalledUpdateShapeSignature = ts.createMap(); var useOldState = canReuseOldState(referencedMap, oldState); for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { @@ -68488,28 +69406,35 @@ var ts; if (newReferences) { referencedMap.set(sourceFile.path, newReferences); } + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } } fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); } return { fileInfos: fileInfos, referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, allFilesExcludingDefaultLibraryFile: undefined, allFileNames: undefined }; } BuilderState.create = create; - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { var signatureCache = cacheToUpdateSignature || ts.createMap(); var sourceFile = programOfThisState.getSourceFileByPath(path); if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); if (!cacheToUpdateSignature) { updateSignaturesFromCache(state, signatureCache); } @@ -68523,8 +69448,9 @@ var ts; }); } BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { return false; } @@ -68540,6 +69466,9 @@ var ts; var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, true, cancellationToken); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } } else { latestSignature = prevSignature; @@ -68548,6 +69477,37 @@ var ts; cacheToUpdateSignature.set(sourceFile.path, latestSignature); return !prevSignature || latestSignature !== prevSignature; } + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; function getAllDependencies(state, programOfThisState, sourceFile) { var _a; var compilerOptions = programOfThisState.getCompilerOptions(); @@ -68627,7 +69587,7 @@ var ts; } return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -68643,7 +69603,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { queue.push.apply(queue, getReferencedByPaths(state, currentPath)); } } @@ -68666,7 +69626,8 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); if (useOldState) { if (!oldState.currentChangedFilePath) { ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); @@ -68692,6 +69653,10 @@ var ts; var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); } } }); @@ -68704,13 +69669,13 @@ var ts; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { - var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var seenAffectedFiles = state.seenAffectedFiles; var affectedFilesIndex = state.affectedFilesIndex; while (affectedFilesIndex < affectedFiles.length) { var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.path)) { state.affectedFilesIndex = affectedFilesIndex; - semanticDiagnosticsPerFile.delete(affectedFile.path); + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); return affectedFile; } seenAffectedFiles.set(affectedFile.path, true); @@ -68720,6 +69685,7 @@ var ts; state.currentChangedFilePath = undefined; ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); state.affectedFiles = undefined; } var nextKey = state.changedFilesSet.keys().next(); @@ -68732,13 +69698,49 @@ var ts; return state.program; } state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; - state.semanticDiagnosticsPerFile.delete(nextKey.value); state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + return; + } + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + })) { + return; + } + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + }); + } + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + }); + } + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return false; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } function doneWithAffectedFile(state, affected) { if (affected === state.program) { state.changedFilesSet.clear(); @@ -68942,6 +69944,7 @@ var ts; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); var resolvedModuleNames = ts.createMap(); @@ -68987,6 +69990,7 @@ var ts; function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); @@ -69022,17 +70026,19 @@ var ts; perDirectoryResolvedModuleNames.clear(); nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); - clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); @@ -69077,7 +70083,7 @@ var ts; perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); - watchFailedLookupLocationOfResolution(resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } @@ -69160,12 +70166,20 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - return { dir: rootDir, dirPath: rootPath }; + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; + } } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { - while (ts.stringContains(dirPath, "/node_modules/")) { + while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } @@ -69192,15 +70206,24 @@ var ts; function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); } - function watchFailedLookupLocationOfResolution(resolution) { - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { - return; - } - if (resolution.refCount !== undefined) { - resolution.refCount++; - return; + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } } - resolution.refCount = 1; + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); var failedLookupLocations = resolution.failedLookupLocations; var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { @@ -69213,6 +70236,7 @@ var ts; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); } if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); setAtRoot = true; } else { @@ -69221,9 +70245,18 @@ var ts; } } if (setAtRoot) { - setDirectoryWatcher(rootDir, rootPath); + setDirectoryWatcher(rootDir, rootPath, true); } } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { @@ -69235,7 +70268,7 @@ var ts; } } function stopWatchFailedLookupLocationOfResolution(resolution) { - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + if (!resolution.refCount) { return; } resolution.refCount--; @@ -69425,15 +70458,24 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { - function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences) { + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, toFileName, info.getCanonicalFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences) { + function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { + var isBundle = (compilerOptions.out || compilerOptions.outFile); + if (isBundle && host.getCommonSourceDirectory) { + compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); + } + var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; + return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + } + moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) return [[ambient]]; @@ -69441,7 +70483,8 @@ var ts; if (!files) { return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); } - var modulePaths = getAllModulePaths(files, ts.getSourceFileOfNode(moduleSymbol.valueDeclaration).fileName, info.getCanonicalFileName, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); @@ -69498,60 +70541,60 @@ var ts; return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js") : undefined; }) || false; } - function discoverProbableSymlinks(files, getCanonicalFileName, host) { + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); var symlinks = ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; }); }); - var result = ts.createMap(); - if (symlinks) { - var currentDirectory = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { - var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; - var resolvedParts = ts.getPathComponents(ts.toPath(resolvedPath, currentDirectory, getCanonicalFileName)); - var originalParts = ts.getPathComponents(ts.toPath(originalPath, currentDirectory, getCanonicalFileName)); - while (compareStrings(resolvedParts[resolvedParts.length - 1], originalParts[originalParts.length - 1]) === 0) { - resolvedParts.pop(); - originalParts.pop(); - } - result.set(ts.getPathFromPathComponents(originalParts), ts.getPathFromPathComponents(resolvedParts)); - } + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); } return result; } - function getAllModulePathsUsingIndirectSymlinks(files, target, getCanonicalFileName, host) { - var links = discoverProbableSymlinks(files, getCanonicalFileName, host); - var paths = ts.arrayFrom(links.keys()); - var options; + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, paths_2 = paths; _i < paths_2.length; _i++) { - var path = paths_2[_i]; - var resolved = links.get(path); - if (compareStrings(target.slice(0, resolved.length + 1), resolved + "/") === 0) { - var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - if (!options) - options = []; - options.push(option); - } + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); } - } - if (options) { - options.push(target); - return options; - } - return [target]; - } - function getAllModulePaths(files, importedFileName, getCanonicalFileName, host) { - var symlinks = ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === importedFileName ? res.originalPath : undefined; - }); }); - return symlinks.length === 0 ? getAllModulePathsUsingIndirectSymlinks(files, ts.getNormalizedAbsolutePath(importedFileName, host.getCurrentDirectory ? host.getCurrentDirectory() : ""), getCanonicalFileName, host) : symlinks; + result.push.apply(result, targets); + return result; } function getRelativePathNParents(relativePath) { var components = ts.getPathComponents(relativePath); @@ -69564,8 +70607,8 @@ var ts; return components.length - 1; } function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { return decl.name.text; } } @@ -69575,10 +70618,7 @@ var ts; var patternText_1 = _a[_i]; var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { + if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && @@ -69669,7 +70709,7 @@ var ts; partEnd = fullPath.indexOf("/", partStart + 1); switch (state) { case 0: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { topLevelNodeModulesIndex = partStart; topLevelPackageNameIndex = partEnd; state = 1; @@ -69686,7 +70726,7 @@ var ts; } break; case 3: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { state = 1; } else { @@ -69845,6 +70885,7 @@ var ts; createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; } var host = system; + host; var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); @@ -69963,16 +71004,15 @@ var ts; onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic }; var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); - if (configFileName) { + if (configFileName && !host.configFileParsingResult) { newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); - if (host.configFileParsingResult) { - setConfigFileParsingResult(host.configFileParsingResult); - } - else { - ts.Debug.assert(!rootFileNames); - parseConfigFile(); - } + ts.Debug.assert(!rootFileNames); + parseConfigFile(); newLine = updateNewLine(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); @@ -70460,7 +71500,7 @@ var ts; } var outputs = []; outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); - if (configFile.options.declaration && !ts.fileExtensionIs(inputFileName, ".json")) { + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json")) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); if (configFile.options.declarationMap) { @@ -70475,7 +71515,7 @@ var ts; } var outputs = []; outputs.push(project.options.outFile); - if (project.options.declaration) { + if (ts.getEmitDeclarations(project.options)) { var dts = ts.changeExtension(project.options.outFile, ".d.ts"); outputs.push(dts); if (project.options.declarationMap) { @@ -70624,6 +71664,7 @@ var ts; return builder.cleanAllProjects(); } if (watch) { + builder.buildAllProjects(); builder.startWatching(); return undefined; } @@ -70675,7 +71716,7 @@ var ts; if (!graph.buildQueue) { return; } - var _loop_11 = function (resolved) { + var _loop_10 = function (resolved) { var cfg = configFileCache.parseConfigFile(resolved); if (cfg) { system.watchFile(resolved, function () { @@ -70699,7 +71740,7 @@ var ts; }; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var resolved = _a[_i]; - _loop_11(resolved); + _loop_10(resolved); } function invalidateProjectAndScheduleBuilds(resolved) { invalidateProject(resolved); @@ -70858,7 +71899,7 @@ var ts; options: configFile.options }; var program = ts.createProgram(programOptions); - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { resultFlags |= BuildResultFlags.SyntaxErrors; for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { @@ -70868,7 +71909,7 @@ var ts; context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); return resultFlags; } - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { resultFlags |= BuildResultFlags.DeclarationEmitErrors; @@ -70920,15 +71961,16 @@ var ts; if (context.options.dry) { return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) + if (context.options.verbose) { buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { var file = outputs_1[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file)); + priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); } compilerHost.setModifiedTime(file, now); } @@ -71109,7 +72151,7 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile); + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; if (inputTime > newestInputFileTime) { newestInputFileName = inputFile; newestInputFileTime = inputTime; @@ -71134,7 +72176,7 @@ var ts; missingOutputFileName = output; break; } - var outputTime = host.getModifiedTime(output); + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; if (outputTime < oldestOutputFileTime) { oldestOutputFileTime = outputTime; oldestOutputFileName = output; @@ -71153,7 +72195,8 @@ var ts; newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } else { - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, host.getModifiedTime(output)); + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } @@ -71262,7 +72305,7 @@ var ts; case UpToDateStatusType.ContainerOnly: break; default: - ts.assertTypeIsNever(status); + ts.assertType(status); } } ts.formatUpToDateStatus = formatUpToDateStatus; diff --git a/lib/tsserver.js b/lib/tsserver.js index 7dbe902b21ac4..4111b40028b34 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -86,7 +86,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.0"; + ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1697,6 +1697,9 @@ var ts; if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { var candidateNameLowerCase = candidateName.toLowerCase(); if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } return candidate; } if (justCheckExactMatches) { @@ -1907,8 +1910,8 @@ var ts; return function (arg) { return f(arg) || g(arg); }; } ts.or = or; - function assertTypeIsNever(_) { } // tslint:disable-line no-empty - ts.assertTypeIsNever = assertTypeIsNever; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -2370,23 +2373,24 @@ var ts; SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 296] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 297] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 298] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 299] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 300] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 301] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 302] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 303] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 304] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 305] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 306] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 307] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 308] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 309] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -2414,9 +2418,9 @@ var ts; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 302] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 302] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -2744,6 +2748,7 @@ var ts; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; @@ -2777,8 +2782,6 @@ var ts; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasExports"] = 1955] = "HasExports"; - SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; @@ -2832,6 +2835,7 @@ var ts; InternalSymbolName["Resolving"] = "__resolving__"; InternalSymbolName["ExportEquals"] = "export="; InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); /* @internal */ var NodeCheckFlags; @@ -2888,7 +2892,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["UnionOfUnitTypes"] = 67108864] = "UnionOfUnitTypes"; + TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2931,7 +2935,7 @@ var ts; TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotUnit"] = 16749629] = "NotUnit"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2965,6 +2969,7 @@ var ts; ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -3822,52 +3827,80 @@ var ts; */ /*@internal*/ function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); return createDirectoryWatcher; /** * Create the directory watcher for the dirPath. */ function createDirectoryWatcher(dirName, callback) { - var watcher = host.watchDirectory(dirName, function (fileName) { - // Call the actual callback - callback(fileName); - // Iterate through existing children and update the watches if needed - updateChildWatches(result, callback); - }); - var result = { - close: function () { - watcher.close(); - result.childWatches.forEach(ts.closeFileWatcher); - result = undefined; - }, + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { dirName: dirName, - childWatches: ts.emptyArray + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } }; - updateChildWatches(result, callback); - return result; } - function updateChildWatches(watcher, callback) { + function updateChildWatches(dirName, dirPath) { // Iterate through existing children and update the watches if needed - if (watcher) { - watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); } } /** * Watch the directories in the parentDir */ - function watchChildDirectories(parentDir, existingChildWatches, callback) { + function watchChildDirectories(parentDir, existingChildWatches) { var newChildWatches; ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch - return host.filePathComparer(childFullName, host.realpath(childFullName)) === 0 /* EqualTo */ ? childFullName : undefined; - }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); return newChildWatches || ts.emptyArray; /** * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName) { - var result = createDirectoryWatcher(childName, callback); + var result = createDirectoryWatcher(childName); addChildDirectoryWatcher(result); } /** @@ -3894,7 +3927,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; - // TODO: this is used as if it's certainly defined in many places. + // TODO: GH#18217 this is used as if it's certainly defined in many places. ts.sys = (function () { // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual // byte order mark from the specified encoding. Using any other byte order mark does @@ -4003,18 +4036,17 @@ var ts; process.stdout._handle.setBlocking(true); } }, - base64decode: Buffer.from ? function (input) { - return Buffer.from(input, "base64").toString("utf8"); - } : function (input) { - return new Buffer(input, "base64").toString("utf8"); - }, - base64encode: Buffer.from ? function (input) { - return Buffer.from(input).toString("base64"); - } : function (input) { - return new Buffer(input).toString("base64"); - } + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, }; return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } function isFileSystemCaseSensitive() { // win32\win64 are case insensitive platforms if (platform === "win32" || platform === "win64") { @@ -4067,7 +4099,7 @@ var ts; createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : watchDirectoryUsingFsWatch; var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ - filePathComparer: ts.getStringComparer(!useCaseSensitiveFileNames), + useCaseSensitiveFileNames: useCaseSensitiveFileNames, directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, watchDirectory: watchDirectory, @@ -4077,8 +4109,7 @@ var ts; if (recursive) { return watchDirectoryRecursively(directoryName, callback); } - watchDirectory(directoryName, callback); - return undefined; // TODO: GH#18217 + return watchDirectory(directoryName, callback); }; } function createNonPollingWatchFile() { @@ -4761,6 +4792,8 @@ var ts; Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4813,7 +4846,7 @@ var ts; Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), - Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), @@ -5029,6 +5062,9 @@ var ts; Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), 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."), @@ -5115,8 +5151,11 @@ var ts; Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), - _0_was_declared_here: diag(2728, ts.DiagnosticCategory.Error, "_0_was_declared_here_2728", "'{0}' was declared here."), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), 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}'."), @@ -5230,6 +5269,7 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5420,6 +5460,7 @@ var ts; Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5479,12 +5520,14 @@ var ts; Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), - Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Error, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{0}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5514,6 +5557,7 @@ var ts; Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), 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."), @@ -5544,6 +5588,7 @@ var ts; Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), @@ -5554,6 +5599,8 @@ var ts; Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5571,6 +5618,10 @@ var ts; Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), 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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5633,6 +5684,8 @@ var ts; Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), }; })(ts || (ts = {})); var ts; @@ -7386,6 +7439,7 @@ var ts; } function scanJSDocToken() { startPos = tokenPos = pos; + tokenFlags = 0; if (pos >= end) { return token = 1 /* EndOfFileToken */; } @@ -7404,6 +7458,7 @@ var ts; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: return token = 39 /* AsteriskToken */; @@ -7538,6 +7593,7 @@ var ts; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -7646,6 +7702,19 @@ var ts; return undefined; } ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; function forEachEntry(map, callback) { var _a; var iterator = map.entries(); @@ -7869,26 +7938,22 @@ var ts; } ts.nodeIsPresent = nodeIsPresent; /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. + * Prepends statements to an array while taking care of prologue directives. */ - function prependStatements(to, from) { + function addStatementsAfterPrologue(to, from) { if (from === undefined || from.length === 0) return to; - if (to === undefined) - return from.slice(); - var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); - to.unshift.apply(to, from); - if (prologue) { - to.unshift(prologue); + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } } + to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.prependStatements = prependStatements; + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; /** * Determine if the given comment is a triple-slash * @@ -7931,7 +7996,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 303 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8019,11 +8084,6 @@ var ts; return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; - // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' - function escapeLeadingUnderscores(identifier) { - return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); - } - ts.escapeLeadingUnderscores = escapeLeadingUnderscores; // Make an identifier from an external module name by extracting the string after the last "/" and replacing // all non-alphanumeric characters with underscores function makeIdentifierFromModuleName(moduleName) { @@ -8098,6 +8158,10 @@ var ts; return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -8128,6 +8192,18 @@ var ts; } ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 291 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { case 158 /* CallSignature */: case 159 /* ConstructSignature */: @@ -8140,7 +8216,7 @@ var ts; case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: case 240 /* TypeAliasDeclaration */: - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 155 /* Constructor */: @@ -8148,16 +8224,13 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: - case 291 /* JSDocSignature */: return true; default: - ts.assertTypeIsNever(node); + ts.assertType(node); return false; } } - ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { case 247 /* ImportDeclaration */: @@ -8212,11 +8285,11 @@ var ts; return name.escapedText; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return escapeLeadingUnderscores(name.text); + return ts.escapeLeadingUnderscores(name.text); case 147 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } ts.getTextOfPropertyName = getTextOfPropertyName; @@ -8365,9 +8438,7 @@ var ts; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { - return n.kind === 181 /* ImportType */ && - n.argument.kind === 180 /* LiteralType */ && - ts.isStringLiteral(n.argument.literal); + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { @@ -8456,6 +8527,8 @@ var ts; return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case 148 /* TypeParameter */: return node === parent.constraint; + case 301 /* JSDocTemplateTag */: + return node === parent.constraint; case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: case 149 /* Parameter */: @@ -9055,6 +9128,8 @@ var ts; return true; case 209 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 274 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); } @@ -9125,12 +9200,15 @@ var ts; } ts.isStringDoubleQuoted = isStringDoubleQuoted; function getDeclarationOfJSInitializer(node) { - if (!isInJavaScriptFile(node) || !node.parent) { + if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + return undefined; + } name = node.parent.name; decl = node.parent; } @@ -9288,8 +9366,12 @@ var ts; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder function getSpecialPropertyAssignmentKind(expr) { - if (!isInJavaScriptFile(expr) || - expr.operatorToken.kind !== 58 /* EqualsToken */ || + var special = getSpecialPropertyAssignmentKindWorker(expr); + return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getSpecialPropertyAssignmentKindWorker(expr) { + if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } @@ -9300,7 +9382,6 @@ var ts; } return getSpecialPropertyAccessKind(lhs); } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getSpecialPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; @@ -9348,6 +9429,14 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); } @@ -9424,7 +9513,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 301 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9712,7 +9801,10 @@ var ts; } else { var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + return ts.isBinaryExpression(binExp) && + getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name; } } default: @@ -9915,12 +10007,10 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isStringOrNumericLiteral(node) { - var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 8 /* NumericLiteral */; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); } - ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; /** * A declaration has a dynamic name if both of the following are true: * 1. The declaration has a computed property name @@ -9935,7 +10025,7 @@ var ts; ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { return name.kind === 147 /* ComputedPropertyName */ && - !isStringOrNumericLiteral(name.expression) && + !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -9949,22 +10039,24 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 /* Identifier */) { - return name.escapedText; - } - if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(name.text); - } - if (name.kind === 147 /* ComputedPropertyName */) { - var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(nameExpression.text); - } + switch (name.kind) { + case 71 /* Identifier */: + return name.escapedText; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 147 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); } - return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { @@ -9984,7 +10076,7 @@ var ts; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : escapeLeadingUnderscores(node.text); + return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -10105,7 +10197,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return 0; case 206 /* SpreadElement */: return 1; @@ -10483,27 +10575,30 @@ var ts; return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; - function getOwnEmitOutputFilePath(sourceFile, host, extension) { + function getOwnEmitOutputFilePath(fileName, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; if (compilerOptions.outDir) { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); } else { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); } return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; - function getDeclarationEmitOutputFilePath(sourceFile, host) { - var options = host.getCompilerOptions(); + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } - ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; /** * Gets the source files that are expected to have an emit output. * @@ -10535,14 +10630,17 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - var commonSourceDirectory = host.getCommonSourceDirectory(); - var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } - ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); @@ -10615,7 +10713,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 156 /* GetAccessor */ || member.kind === 157 /* SetAccessor */) + if (ts.isAccessor(member) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -10649,7 +10747,10 @@ var ts; * parsed in a JavaScript file, gets the type annotation from JSDoc. */ function getEffectiveTypeAnnotationNode(node) { - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); + var type = node.type; + if (type || !isInJavaScriptFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; function getTypeAnnotationNode(node) { @@ -10661,27 +10762,11 @@ var ts; * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { - if (ts.isJSDocSignature(node)) { - return node.type && node.type.typeExpression && node.type.typeExpression.type; - } - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - /** - * Gets the effective type parameters. If the node was parsed in a - * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. - */ - function getEffectiveTypeParameterDeclarations(node) { - if (ts.isJSDocSignature(node)) { - return ts.emptyArray; - } - if (isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); - return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); - } - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); - } - ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); } @@ -11448,7 +11533,9 @@ var ts; return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; case 202 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; - return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); default: @@ -11978,6 +12065,11 @@ var ts; return undefined; } ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; /** * Remove extra underscore from escaped identifier text content. * @@ -12063,8 +12155,8 @@ var ts; switch (declaration.kind) { case 71 /* Identifier */: return declaration; - case 302 /* JSDocPropertyTag */: - case 296 /* JSDocParameterTag */: { + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: { var name = declaration.name; if (name.kind === 146 /* QualifiedName */) { return name.right; @@ -12083,7 +12175,7 @@ var ts; return undefined; } } - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); case 252 /* ExportAssignment */: { var expression = declaration.expression; @@ -12168,6 +12260,11 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; /** Gets the JSDoc this tag for the node if present */ function getJSDocThisTag(node) { return getFirstJSDocTag(node, ts.isJSDocThisTag); @@ -12213,14 +12310,27 @@ var ts; } ts.getJSDocType = getJSDocType; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node) { var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } } ts.getJSDocReturnType = getJSDocReturnType; /** Get all JSDoc tags related to a node, including those on parent nodes. */ @@ -12244,6 +12354,28 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -12481,7 +12613,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 305 /* PartiallyEmittedExpression */) { + while (node.kind === 306 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -12884,36 +13016,40 @@ var ts; return node.kind === 294 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 296 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 298 /* JSDocThisTag */; + return node.kind === 299 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 296 /* JSDocParameterTag */; + return node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 297 /* JSDocReturnTag */; + return node.kind === 298 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 299 /* JSDocTypeTag */; + return node.kind === 300 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 300 /* JSDocTemplateTag */; + return node.kind === 301 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 301 /* JSDocTypedefTag */; + return node.kind === 302 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 302 /* JSDocPropertyTag */; + return node.kind === 303 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 302 /* JSDocPropertyTag */ || node.kind === 296 /* JSDocParameterTag */; + return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { @@ -12936,7 +13072,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 303 /* SyntaxList */; + return n.kind === 304 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13401,8 +13537,8 @@ var ts; case 206 /* SpreadElement */: case 210 /* AsExpression */: case 208 /* OmittedExpression */: - case 306 /* CommaListExpression */: - case 305 /* PartiallyEmittedExpression */: + case 307 /* CommaListExpression */: + case 306 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13416,12 +13552,12 @@ var ts; ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 305 /* PartiallyEmittedExpression */; + return node.kind === 306 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 304 /* NotEmittedStatement */; + return node.kind === 305 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13532,9 +13668,9 @@ var ts; || kind === 240 /* TypeAliasDeclaration */ || kind === 148 /* TypeParameter */ || kind === 235 /* VariableDeclaration */ - || kind === 301 /* JSDocTypedefTag */ + || kind === 302 /* JSDocTypedefTag */ || kind === 295 /* JSDocCallbackTag */ - || kind === 302 /* JSDocPropertyTag */; + || kind === 303 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { return kind === 237 /* FunctionDeclaration */ @@ -13569,14 +13705,14 @@ var ts; || kind === 217 /* VariableStatement */ || kind === 222 /* WhileStatement */ || kind === 229 /* WithStatement */ - || kind === 304 /* NotEmittedStatement */ - || kind === 308 /* EndOfDeclarationMarker */ - || kind === 307 /* MergeDeclarationMarker */; + || kind === 305 /* NotEmittedStatement */ + || kind === 309 /* EndOfDeclarationMarker */ + || kind === 308 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 300 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -13671,7 +13807,7 @@ var ts; /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 302 /* LastJSDocNode */; + return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ @@ -13682,7 +13818,7 @@ var ts; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 302 /* LastJSDocTagNode */; + return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -13707,45 +13843,6 @@ var ts; return !!node.type; } ts.hasType = hasType; - /* True if the node could have a type node a `.type` */ - /* @internal */ - function couldHaveType(node) { - switch (node.kind) { - case 149 /* Parameter */: - case 151 /* PropertySignature */: - case 152 /* PropertyDeclaration */: - case 153 /* MethodSignature */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 175 /* ParenthesizedType */: - case 177 /* TypeOperator */: - case 179 /* MappedType */: - case 192 /* TypeAssertionExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 210 /* AsExpression */: - case 235 /* VariableDeclaration */: - case 237 /* FunctionDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 281 /* JSDocTypeExpression */: - case 284 /* JSDocNullableType */: - case 285 /* JSDocNonNullableType */: - case 286 /* JSDocOptionalType */: - case 287 /* JSDocFunctionType */: - case 288 /* JSDocVariadicType */: - return true; - } - return false; - } - ts.couldHaveType = couldHaveType; /** True if has initializer node attached to it. */ /* @internal */ function hasInitializer(node) { @@ -13759,18 +13856,7 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - switch (node.kind) { - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return true; - default: - return false; - } + return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ @@ -14028,7 +14114,7 @@ var ts; } ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { - return !!(options.declaration && options.declarationMap); + return !!(getEmitDeclarations(options) && options.declarationMap); } ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { @@ -14048,6 +14134,14 @@ var ts; return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + if (oldOptions === newOptions) { + return false; + } + return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || + (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14212,6 +14306,12 @@ var ts; return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); } ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; function isUrl(path) { return getEncodedRootLength(path) < 0; } @@ -15064,6 +15164,100 @@ var ts; return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); } ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; })(ts || (ts = {})); var ts; (function (ts) { @@ -15481,7 +15675,7 @@ var ts; return visitNode(cbNode, node.expression); case 256 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 258 /* JsxElement */: return visitNode(cbNode, node.openingElement) || @@ -15521,8 +15715,8 @@ var ts; visitNode(cbNode, node.type); case 289 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15531,15 +15725,15 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 297 /* JSDocReturnTag */: + case 298 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); case 293 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 300 /* JSDocTemplateTag */: - return visitNodes(cbNode, cbNodes, node.typeParameters); - case 301 /* JSDocTypedefTag */: + case 301 /* JSDocTemplateTag */: + return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); + case 302 /* JSDocTypedefTag */: if (node.typeExpression && node.typeExpression.kind === 281 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || @@ -15552,13 +15746,15 @@ var ts; case 295 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 298 /* JSDocThisTag */: + case 299 /* JSDocThisTag */: + return visitNode(cbNode, node.typeExpression); + case 296 /* JSDocEnumTag */: return visitNode(cbNode, node.typeExpression); case 291 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || + ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); case 290 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { @@ -15568,7 +15764,7 @@ var ts; } } return; - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -16417,7 +16613,7 @@ var ts; return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); @@ -16440,7 +16636,7 @@ var ts; return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: if (token() === 26 /* CommaToken */) { @@ -16450,13 +16646,15 @@ var ts; case 11 /* ArgumentExpressions */: return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: - return isStartOfParameter(); - case 19 /* TypeArguments */: - case 20 /* TupleElementTypes */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: return token() === 26 /* CommaToken */ || isStartOfType(); - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return isHeritageClause(); - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; @@ -16521,7 +16719,7 @@ var ts; case 6 /* EnumMembers */: case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return token() === 18 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; @@ -16529,24 +16727,25 @@ var ts; return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: return token() === 22 /* CloseBracketToken */; + case 17 /* JSDocParameters */: case 16 /* Parameters */: - case 17 /* RestProperties */: + case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token return token() !== 26 /* CommaToken */; - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; case 13 /* JsxAttributes */: return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; @@ -16579,7 +16778,7 @@ var ts; } // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 23 /* Count */; kind++) { + for (var kind = 0; kind < 24 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; @@ -16691,24 +16890,25 @@ var ts; return isReusableTypeMember(node); case 8 /* VariableDeclarations */: return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -16716,7 +16916,7 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. @@ -16866,7 +17066,7 @@ var ts; case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected; case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; - case 17 /* RestProperties */: // fallthrough + case 18 /* RestProperties */: // fallthrough case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; @@ -16877,12 +17077,13 @@ var ts; case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected; case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; + case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected; case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 18 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; - case 19 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 20 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; - case 21 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; - case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; + case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; + case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; + case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` @@ -17082,7 +17283,7 @@ var ts; var node = createNode(162 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } return finishNode(node); } @@ -17180,7 +17381,7 @@ var ts; } function parseJSDocType() { var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); - var type = parseType(); + var type = parseTypeOrTypePredicate(); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -17226,7 +17427,7 @@ var ts; } function parseTypeParameters() { if (token() === 27 /* LessThanToken */) { - return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } } function parseParameterType() { @@ -17235,12 +17436,12 @@ var ts; } return undefined; } - function isStartOfParameter() { + function isStartOfParameter(isJSDocParameter) { return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 /* AtToken */ || - isStartOfType(/*inStartOfParameter*/ true); + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { var node = createNodeWithJSDoc(149 /* Parameter */); @@ -17326,7 +17527,9 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1 /* Yield */)); setAwaitContext(!!(flags & 2 /* Await */)); - signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return parseExpected(20 /* CloseParenToken */); @@ -17564,7 +17767,7 @@ var ts; } function parseTupleType() { var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { @@ -17717,6 +17920,8 @@ var ts; case 126 /* InferKeyword */: case 91 /* ImportKeyword */: return true; + case 89 /* FunctionKeyword */: + return !inStartOfParameter; case 38 /* MinusToken */: return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19 /* OpenParenToken */: @@ -17729,7 +17934,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); @@ -18223,8 +18428,9 @@ var ts; return 1 /* True */; } // If we had "(" followed by something that's not an identifier, - // then this definitely doesn't look like a lambda. - if (!isIdentifier()) { + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 99 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { @@ -19059,7 +19265,7 @@ var ts; } else { var argument = allowInAnd(parseExpression); - if (ts.isStringOrNumericLiteral(argument)) { + if (ts.isStringOrNumericLiteralLike(argument)) { argument.text = internIdentifier(argument.text); } indexedAccess.argumentExpression = argument; @@ -19130,7 +19336,7 @@ var ts; if (!parseOptional(27 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; @@ -20282,7 +20488,7 @@ var ts; // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } if (isHeritageClause()) { - return parseList(21 /* HeritageClauses */, parseHeritageClause); + return parseList(22 /* HeritageClauses */, parseHeritageClause); } return undefined; } @@ -20303,7 +20509,7 @@ var ts; } function tryParseTypeArguments() { return token() === 27 /* LessThanToken */ - ? parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) : undefined; } function isHeritageClause() { @@ -20529,7 +20735,7 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { @@ -20643,13 +20849,14 @@ var ts; ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; - ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; // Number of parsing contexts + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -20766,7 +20973,7 @@ var ts; switch (token()) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -20826,7 +21033,7 @@ var ts; nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return createJSDocComment(); }); function removeLeadingNewlines(comments) { @@ -20834,8 +21041,8 @@ var ts; comments.shift(); } } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { comments.pop(); } } @@ -20867,13 +21074,30 @@ var ts; nextJSDocToken(); } } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 39 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } function parseTag(indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": @@ -20887,6 +21111,9 @@ var ts; case "this": tag = parseThisTag(atToken, tagName); break; + case "enum": + tag = parseEnumTag(atToken, tagName); + break; case "arg": case "argument": case "param": @@ -20984,7 +21211,7 @@ var ts; tok = nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { @@ -21007,7 +21234,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespace(); + skipWhitespaceOrAsterisk(); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -21041,15 +21268,15 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespace(); + skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(302 /* JSDocPropertyTag */, atToken.pos) : - createNode(296 /* JSDocParameterTag */, atToken.pos); + createNode(303 /* JSDocPropertyTag */, atToken.pos) : + createNode(297 /* JSDocParameterTag */, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -21075,7 +21302,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) { + if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } } @@ -21091,20 +21318,20 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 297 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(297 /* JSDocReturnTag */, atToken.pos); + var result = createNode(298 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 299 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(299 /* JSDocTypeTag */, atToken.pos); + var result = createNode(300 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); @@ -21145,7 +21372,15 @@ var ts; return finishNode(tag); } function parseThisTag(atToken, tagName) { - var tag = createNode(298 /* JSDocThisTag */, atToken.pos); + var tag = createNode(299 /* JSDocThisTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(atToken, tagName) { + var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); @@ -21155,7 +21390,7 @@ var ts; function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(301 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); @@ -21168,12 +21403,12 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = scanner.getStartPos(); + var start_3 = atToken.pos; while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 299 /* JSDocTypeTag */) { + if (child.kind === 300 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21236,7 +21471,7 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(57 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 297 /* JSDocReturnTag */) { + if (tag && tag.kind === 298 /* JSDocReturnTag */) { return tag; } } @@ -21281,7 +21516,7 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) && + if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -21350,16 +21585,14 @@ var ts; skipWhitespace(); var typeParameter = createNode(148 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); - skipWhitespace(); finishNode(typeParameter); + skipWhitespace(); typeParameters.push(typeParameter); } while (parseOptionalJsdoc(26 /* CommaToken */)); - if (constraint) { - ts.first(typeParameters).constraint = constraint.type; - } - var result = createNode(300 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; + result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); return result; @@ -21885,9 +22118,11 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + ts.isDeclarationFileName = isDeclarationFileName; /*@internal*/ function processCommentPragmas(context, sourceText) { var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); @@ -22431,13 +22666,15 @@ var ts; { name: "noImplicitAny", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type }, { name: "strictNullChecks", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks @@ -22445,6 +22682,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types @@ -22452,6 +22690,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes @@ -22459,6 +22698,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, @@ -22466,6 +22706,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file @@ -22474,6 +22715,7 @@ var ts; { name: "noUnusedLocals", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_locals, @@ -22481,6 +22723,7 @@ var ts; { name: "noUnusedParameters", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_parameters, @@ -22488,6 +22731,7 @@ var ts; { name: "noImplicitReturns", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value @@ -22495,6 +22739,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement @@ -22565,12 +22810,14 @@ var ts; { name: "allowSyntheticDefaultImports", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, { name: "esModuleInterop", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports @@ -22746,6 +22993,7 @@ var ts; { name: "noImplicitUseStrict", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output }, @@ -22784,24 +23032,28 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels }, { name: "allowUnreachableCode", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code }, { name: "suppressExcessPropertyErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, }, { name: "suppressImplicitAnyIndexErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, @@ -22820,6 +23072,7 @@ var ts; { name: "noStrictGenericChecks", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, }, @@ -23341,9 +23594,10 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); - var option = knownOptions ? knownOptions.get(keyText) : undefined; - if (extraKeyDiagnosticMessage && !option) { + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); @@ -24418,9 +24672,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -24649,9 +24903,7 @@ var ts; return perFolderCache; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; // TODO: GH#18217 - } + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { perModuleNameCache = createPerModuleNameCache(); @@ -24683,41 +24935,45 @@ var ts; return; } directoryPathMap.set(path, result); - var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); // find common prefix between directory and resolved file name - // this common prefix should be the shorted path that has the same resolution + // this common prefix should be the shortest path that has the same resolution // directory: /a/b/c/d/e // resolvedFileName: /a/b/foo.d.ts - var commonPrefix = getCommonPrefix(path, resolvedFileName); + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); var current = path; - while (true) { + while (current !== commonPrefix) { var parent = ts.getDirectoryPath(current); if (parent === current || directoryPathMap.has(parent)) { break; } directoryPathMap.set(parent, result); current = parent; - if (current === commonPrefix) { - break; - } } } function getCommonPrefix(directory, resolution) { - if (resolution === undefined) { - return undefined; - } var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); // find first position where directory and resolution differs var i = 0; - while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { i++; } - // find last directory separator before position i - var sep = directory.lastIndexOf(ts.directorySeparator, i); - if (sep < 0) { + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { + return undefined; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { return undefined; } - return directory.substr(0, sep); + return directory.substr(0, Math.max(sep, rootLength)); } } } @@ -24766,10 +25022,9 @@ var ts; } if (perFolderCache) { perFolderCache.set(moduleName, result); - // put result in per-module name cache - var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); - if (perModuleNameCache) { - perModuleNameCache.set(containingDirectory, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); } } } @@ -24994,15 +25249,15 @@ var ts; tryResolve(Extensions.JavaScript) || (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { @@ -25012,17 +25267,13 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - var originalPath = void 0; - if (!compilerOptions.preserveSymlinks && resolvedValue) { - originalPath = resolvedValue.path; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - if (path === originalPath) { - originalPath = undefined; - } - resolvedValue = __assign({}, resolvedValue, { path: path }); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -25075,7 +25326,8 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } - var nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -25089,11 +25341,11 @@ var ts; */ function parseNodeModuleFromPath(resolved) { var path = ts.normalizePath(resolved.path); - var idx = path.lastIndexOf(nodeModulesPathPart); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; } - var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); @@ -25436,7 +25688,7 @@ var ts; trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -25446,17 +25698,17 @@ var ts; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*originalPath*/ undefined, /*isExternalLibraryImport*/ false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -25491,7 +25743,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*originalPath*/ undefined, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -25699,10 +25951,10 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; symbol.declarations = ts.append(symbol.declarations, node); - if (symbolFlags & 1955 /* HasExports */ && !symbol.exports) { + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } - if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } if (symbolFlags & 67216319 /* Value */) { @@ -25729,7 +25981,7 @@ var ts; if (name.kind === 147 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression)) { + if (ts.isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -25774,7 +26026,7 @@ var ts; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); // TODO: GH#18217 + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); } /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @@ -25845,8 +26097,10 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; } if (symbol.declarations && symbol.declarations.length) { // If the current node is a default export of some sort, then check if @@ -25854,6 +26108,7 @@ var ts; // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } else { // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. @@ -25863,13 +26118,15 @@ var ts; if (symbol.declarations && symbol.declarations.length && (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } } } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); symbol = createSymbol(0 /* None */, name); } } @@ -26140,7 +26397,7 @@ var ts; case 189 /* CallExpression */: bindCallExpressionFlow(node); break; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; @@ -26165,6 +26422,7 @@ var ts; case 71 /* Identifier */: case 99 /* ThisKeyword */: case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return isNarrowableReference(expr); case 189 /* CallExpression */: return hasNarrowableArgument(expr); @@ -26178,10 +26436,11 @@ var ts; return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || - expr.kind === 99 /* ThisKeyword */ || - expr.kind === 97 /* SuperKeyword */ || - expr.kind === 187 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -26617,7 +26876,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -26906,7 +27165,7 @@ var ts; case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: case 287 /* JSDocFunctionType */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: case 240 /* TypeAliasDeclaration */: case 179 /* MappedType */: @@ -27244,13 +27503,26 @@ var ts; errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } - function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); if (isError) { file.bindDiagnostics.push(diag); } @@ -27370,12 +27642,19 @@ var ts; } return checkStrictModeIdentifier(node); case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } + if (ts.isInJavaScriptFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(container, "module")) { + declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + } break; case 202 /* BinaryExpression */: var specialKind = ts.getSpecialPropertyAssignmentKind(node); @@ -27417,6 +27696,8 @@ var ts; return checkStrictModePrefixUnaryExpression(node); case 229 /* WithStatement */: return checkStrictModeWithStatement(node); + case 231 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); case 176 /* ThisType */: seenThisKeyword = true; return; @@ -27520,7 +27801,7 @@ var ts; // falls through case 243 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: if (node.parent.kind === 291 /* JSDocSignature */) { return bindParameter(node); } @@ -27528,13 +27809,13 @@ var ts; break; } // falls through - case 302 /* JSDocPropertyTag */: + case 303 /* JSDocPropertyTag */: var propTag = node; var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } @@ -27739,6 +28020,11 @@ var ts; } function bindSpecialPropertyAssignment(node) { var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } // Fix up parent pointers since we're going to use these nodes before we bind into them node.left.parent = node; node.right.parent = node; @@ -27922,7 +28208,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 296 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -28046,18 +28332,48 @@ var ts; // - node is not block scoped variable statement and at least one variable declaration has initializer // Rationale: we don't want to report errors on non-initialized var's since they are hoisted // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var isError = ts.unreachableCodeIsError(options) && + var isError_1 = ts.unreachableCodeIsError(options) && !(node.flags & 4194304 /* Ambient */) && (!ts.isVariableStatement(node) || !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || node.declarationList.declarations.some(function (d) { return !!d.initializer; })); - errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); } } } return true; } } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return true; + case 242 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 241 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || @@ -28631,7 +28947,7 @@ var ts; break; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; @@ -28908,7 +29224,7 @@ var ts; return 940049729 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: case 193 /* ParenthesizedExpression */: case 97 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; @@ -28932,7 +29248,7 @@ var ts; /** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -29008,7 +29324,7 @@ var ts; ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { - visitType(getConstraintFromTypeParameter(type)); + visitType(getConstraintOfTypeParameter(type)); } function visitUnionOrIntersectionType(type) { ts.forEach(type.types, visitType); @@ -29080,7 +29396,7 @@ var ts; } var t = getTypeOfSymbol(symbol); visitType(t); // Should handle members on classes and such - if (symbol.flags & 1955 /* HasExports */) { + if (symbol.exports) { symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { @@ -29170,7 +29486,6 @@ var ts; undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); - var moduleSymbol = createSymbol(4 /* Property */, "module"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; // for public members that accept a Node or one of its subtypes, we must guard against @@ -29214,6 +29529,7 @@ var ts; return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, getReturnTypeOfSignature: getReturnTypeOfSignature, getNullableType: getNullableType, getNonNullableType: getNonNullableType, @@ -29282,6 +29598,10 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); @@ -29292,12 +29612,11 @@ var ts; }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { - var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); - apparentArgumentCount = theArgumentCount; - var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; - apparentArgumentCount = undefined; - return res; + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); }, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); @@ -29334,7 +29653,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); @@ -29377,7 +29696,7 @@ var ts; getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentModule: function (node, target) { return getSuggestionForNonexistentModule(node, target); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -29396,6 +29715,9 @@ var ts; return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } var diagnostics; try { // Record the cancellation token so it can be checked later on during checkSourceElement. @@ -29415,8 +29737,8 @@ var ts; cancellationToken = undefined; } function addUnusedDiagnostics() { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { - if (!unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } }); @@ -29432,6 +29754,13 @@ var ts; } } }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } var tupleTypes = ts.createMap(); var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); @@ -29487,7 +29816,6 @@ var ts; var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); @@ -29659,7 +29987,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30101,6 +30429,7 @@ var ts; // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) // or if usage is in a type context: // 1. inside a type query (typeof in type position) + // 2. inside a jsdoc comment if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; @@ -30110,7 +30439,7 @@ var ts; return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { @@ -30393,7 +30722,7 @@ var ts; location = location.parent; } break; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); @@ -30427,10 +30756,6 @@ var ts; if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } - if (ts.isIdentifier(originalLocation) && ts.isPropertyAccessExpression(originalLocation.parent) && - originalLocation.escapedText === "module" && originalLocation.parent.name.escapedText === "exports") { - return moduleSymbol; - } } } if (!result) { @@ -30443,9 +30768,13 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { - suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } } if (!suggestion) { @@ -30654,7 +30983,7 @@ var ts; ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } } @@ -30798,7 +31127,7 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } } } @@ -30833,9 +31162,13 @@ var ts; if (!symbol) { var moduleName = getFullyQualifiedName(moduleSymbol); var declarationName = ts.declarationNameToString(name); - var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); @@ -31157,6 +31490,12 @@ var ts; var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -31169,8 +31508,8 @@ var ts; var errorInfo = packageId ? ts.chainDiagnosticMessages( /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0 - : ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)) + ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 + : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } @@ -31315,13 +31654,13 @@ var ts; } function getExportsOfModuleWorker(moduleSymbol) { var visitedSymbols = []; - // A module defined by an 'export=' consists on one export that needs to be resolved + // A module defined by an 'export=' consists of one export that needs to be resolved moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; // 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 & 1955 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { return; } var symbols = ts.cloneMap(symbol.exports); @@ -31366,17 +31705,25 @@ var ts; * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` */ - function getContainerOfSymbol(symbol) { + function getContainersOfSymbol(symbol, enclosingDeclaration) { var container = getParentOfSymbol(symbol); if (container) { - return container; + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + } + return ts.append(additionalContainers, container); } - var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); - if (!candidate) { + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { return undefined; } - var alias = getAliasForSymbolInContainer(candidate, symbol); - return alias ? candidate : undefined; + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { @@ -31400,9 +31747,7 @@ var ts; } } function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); @@ -31627,6 +31972,54 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -31637,55 +32030,20 @@ var ts; */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, - }; - } - return hasAccessibleDeclarations; - } - else { - if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { - // Any meaning of a module symbol is always accessible via an `import` type - return { - accessibility: 0 /* Accessible */ - }; - } - } - // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. - // It could be a qualified symbol and hence verify the path - // e.g.: - // module m { - // export class c { - // } - // } - // const x: typeof m.c - // In the above example when we start with checking if typeof m.c symbol is accessible, - // we are going to see if c can be accessed in scope directly. - // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible - // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getContainerOfSymbol(symbol); + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { accessibility: 2 /* CannotBeNamed */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), errorModuleName: symbolToString(symbolExternalModule) }; } @@ -31693,14 +32051,14 @@ var ts; // Just a local name that is not accessible return { accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 /* Accessible */ }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); @@ -31821,7 +32179,8 @@ var ts; function typeToString(type, enclosingDeclaration, flags, writer) { if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -31829,7 +32188,7 @@ var ts; var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } @@ -31874,11 +32233,17 @@ var ts; tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, - inferTypeParameters: undefined + inferTypeParameters: undefined, + approximateLength: 0 }; var resultingNode = cb(context); return context.encounteredError ? undefined : resultingNode; } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + } function typeToTypeNodeHelper(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); @@ -31890,66 +32255,83 @@ var ts; return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { return ts.createKeywordTypeNode(142 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(137 /* StringKeyword */); } if (type.flags & 8 /* Number */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(134 /* NumberKeyword */); } if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (type.flags & (64 /* StringLiteral */)) { + if (type.flags & 64 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & (128 /* NumberLiteral */)) { + if (type.flags & 128 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 256 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 2048 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } + context.approximateLength += 13; return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); } if (type.flags & 4096 /* Void */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(105 /* VoidKeyword */); } if (type.flags & 8192 /* Undefined */) { + context.approximateLength += 9; return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); } if (type.flags & 16384 /* Null */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(95 /* NullKeyword */); } if (type.flags & 32768 /* Never */) { + context.approximateLength += 5; return ts.createKeywordTypeNode(131 /* NeverKeyword */); } if (type.flags & 1024 /* ESSymbol */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(138 /* SymbolKeyword */); } if (type.flags & 16777216 /* NonPrimitive */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(135 /* ObjectKeyword */); } if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { @@ -31961,6 +32343,7 @@ var ts; context.tracker.reportInaccessibleThisError(); } } + context.approximateLength += 4; return ts.createThis(); } var objectFlags = ts.getObjectFlags(type); @@ -31970,6 +32353,7 @@ var ts; } if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && @@ -31978,7 +32362,9 @@ var ts; ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { - return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol @@ -31993,7 +32379,7 @@ var ts; } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; - var typeNodes = mapToTypeNodes(types, context); + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; @@ -32012,12 +32398,14 @@ var ts; } if (type.flags & 1048576 /* Index */) { var indexedType = type.type; + context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 2097152 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } if (type.flags & 4194304 /* Conditional */) { @@ -32028,6 +32416,7 @@ var ts; context.inferTypeParameters = saveInferTypeParameters; var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 8388608 /* Substitution */) { @@ -32050,6 +32439,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { @@ -32058,7 +32448,7 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); @@ -32077,6 +32467,7 @@ var ts; return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); } else { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } } @@ -32118,6 +32509,7 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { @@ -32136,6 +32528,7 @@ var ts; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function typeReferenceToTypeNode(type) { @@ -32252,6 +32645,9 @@ var ts; return ids; } function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; @@ -32274,8 +32670,10 @@ var ts; if (!properties) { return typeElements; } + var i = 0; for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + i++; if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { if (propertySymbol.flags & 4194304 /* Prototype */) { continue; @@ -32284,61 +32682,96 @@ var ts; context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); } } - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? - anyType : getTypeOfSymbol(propertySymbol); - var saveEnclosingDeclaration = context.enclosingDeclaration; - context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } - } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); - context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; - if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { - var signatures = getSignaturesOfType(propertyType, 0 /* Call */); - for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { - var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); - } - typeElements.push(methodDeclaration); - } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); } - else { - var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; - var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined); - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); - } - typeElements.push(propertySignature); + } + } + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); } + typeElements.push(methodDeclaration); } - return typeElements.length ? typeElements : undefined; + } + else { + var savedFlags = context.flags; + context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); } } - function mapToTypeNodes(types, context) { + function mapToTypeNodes(types, context, isBareList) { if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } var result = []; + var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -32360,6 +32793,7 @@ var ts; if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } + context.approximateLength += (name.length + 4); return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } @@ -32398,6 +32832,7 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { @@ -32419,14 +32854,14 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 296 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32448,6 +32883,7 @@ var ts; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); @@ -32477,16 +32913,18 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); - var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents)) { + for (var _i = 0, _a = parents; _i < _a.length; _i++) { + var parent = _a[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } } } } @@ -32496,10 +32934,12 @@ var ts; if ( // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } return [symbol]; } } @@ -32554,24 +32994,26 @@ var ts; } } } - return symbol.escapedName.substring(1, symbol.escapedName.length - 1); - } - else { - if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { - // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); - var links = getSymbolLinks(symbol); - var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); - if (!specifier) { - specifier = ts.flatten(ts.moduleSpecifiers.getModuleSpecifiers(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, context.tracker.moduleResolverHost.getSourceFiles(), // TODO: GH#18217 - { importModuleSpecifierPreference: "non-relative" }))[0]; - links.specifierCache = links.specifierCache || ts.createMap(); - links.specifierCache.set(contextFile.path, specifier); + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - return specifier; + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); } + return specifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module @@ -32580,7 +33022,11 @@ var ts; // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); - var lit = ts.createLiteralTypeNode(ts.createLiteral(getSpecifierForModuleSymbol(chain[0], context))); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") if (!nonRootParts || ts.isEntityName(nonRootParts)) { if (nonRootParts) { var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; @@ -32614,6 +33060,7 @@ var ts; context.flags |= 16777216 /* InInitialEntityName */; } var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } @@ -32828,7 +33275,7 @@ var ts; function determineIfDeclarationIsVisible() { switch (node.kind) { case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); @@ -32981,23 +33428,19 @@ var ts; return -1; } function hasType(target, propertyName) { - if (propertyName === 0 /* Type */) { - return !!getSymbolLinks(target).type; - } - if (propertyName === 2 /* DeclaredType */) { - return !!getSymbolLinks(target).declaredType; - } - if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return !!target.resolvedBaseConstructorType; - } - if (propertyName === 3 /* ResolvedReturnType */) { - return !!target.resolvedReturnType; - } - if (propertyName === 4 /* ResolvedBaseConstraint */) { - var bc = target.resolvedBaseConstraint; - return !!bc && bc !== circularConstraintType; - } - return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + } + return ts.Debug.assertNever(propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -33044,7 +33487,7 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); @@ -33062,10 +33505,9 @@ var ts; } for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; - var inNamesToRemove = names.has(prop.escapedName); - var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); - var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); - if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { + if (!names.has(prop.escapedName) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { members.set(prop.escapedName, getNonReadonlySymbol(prop)); } } @@ -33273,17 +33715,17 @@ var ts; } } // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.escapedName === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } + else if (ts.isInJavaScriptFile(declaration)) { + var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); + if (expandoType) { + return expandoType; + } + } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); @@ -33301,96 +33743,46 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); if (specialDeclaration) { - return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var tag = ts.getJSDocTypeTag(specialDeclaration); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); + return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); } - var types = []; - var constructorTypes; var definedInConstructor = false; var definedInMethod = false; - var jsDocType; - var _loop_4 = function (declaration) { - var declarationInConstructor = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; var expression = ts.isBinaryExpression(declaration) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { - return { value: errorType }; + return errorType; } var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); if (special === 4 /* ThisProperty */) { - var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); - // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. - // Function expressions that are assigned to the prototype count as methods. - declarationInConstructor = thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 237 /* FunctionDeclaration */ || - (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); - if (declarationInConstructor) { + if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } else { definedInMethod = true; } } - // If there is a JSDoc type, use it - var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type_1) { - var declarationType = getWidenedType(type_1); - if (!jsDocType) { - jsDocType = declarationType; - } - else if (jsDocType !== errorType && declarationType !== errorType && - !isTypeIdenticalTo(jsDocType, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { - errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); - } - } - else if (!jsDocType && ts.isBinaryExpression(expression)) { - // If we don't have an explicit JSDoc type, get the type from the expression. - var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); - if (ts.getObjectFlags(type_2) & 16 /* Anonymous */ && - special === 2 /* ModuleExports */ && - symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type_2); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); - symbol.exports.forEach(function (s, name) { - if (members_3.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); - } - else { - members_3.set(name, s); - } - }); - type_2 = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); - } - var anyedType = type_2; - if (isEmptyArrayLiteralType(type_2)) { - anyedType = anyArrayType; - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } - } - types.push(anyedType); - if (declarationInConstructor) { - (constructorTypes || (constructorTypes = [])).push(anyedType); - } + jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!jsdocType) { + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); } - }; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var state_2 = _loop_4(declaration); - if (typeof state_2 === "object") - return state_2.value; } - var type = jsDocType; + var type = jsdocType; if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfSpecialPropertyOfBaseType(symbol); @@ -33411,6 +33803,91 @@ var ts; } return widened; } + function getJSExpandoObjectType(decl, symbol, init) { + if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 131072 /* Object */ && + special === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 155 /* Constructor */ || + thisContainer.kind === 237 /* FunctionDeclaration */ || + (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } /** check for definition in base class if any declaration is in a class */ function getTypeOfSpecialPropertyOfBaseType(specialProperty) { var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { @@ -33548,138 +34025,104 @@ var ts; } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - // Handle prototype property - if (symbol.flags & 4194304 /* Prototype */) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - // CommonsJS require and module both have type any. - if (symbol === requireSymbol || symbol === moduleSymbol) { - return links.type = anyType; - } - // Handle catch clause variables - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; - } - if (declaration.kind === 252 /* ExportAssignment */) { - return links.type = checkExpression(declaration.expression); - } - // Handle variable, parameter or property - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; - } - var type = getJSSpecialType(symbol, declaration); - if (!type) { - if (ts.isJSDocPropertyLikeTag(declaration) - || ts.isPropertyAccessExpression(declaration) - || ts.isIdentifier(declaration) - || ts.isClassDeclaration(declaration) - || ts.isFunctionDeclaration(declaration) - || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { - // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - return getTypeOfFuncClassEnumModule(symbol); - } - type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; - } - else if (ts.isPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); - } - else if (ts.isJsxAttribute(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); - } - else if (ts.isShorthandPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); - } - else if (ts.isObjectLiteralMethod(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); - } - else if (ts.isParameter(declaration) - || ts.isPropertyDeclaration(declaration) - || ts.isPropertySignature(declaration) - || ts.isVariableDeclaration(declaration) - || ts.isBindingElement(declaration)) { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); - } - else { - return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); - } - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); } - function getJSSpecialType(symbol, decl) { - if (!ts.isInJavaScriptFile(decl)) { - return undefined; + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } + if (declaration.kind === 252 /* ExportAssignment */) { + return checkExpression(declaration.expression); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJavaScriptFile(declaration) && + (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromJSPropertyAssignments(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } - else if (ts.isJSDocPropertyLikeTag(decl) && decl.typeExpression) { - return getTypeFromTypeNode(decl.typeExpression.type); - } - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - else if (ts.isBinaryExpression(decl) || - ts.isPropertyAccessExpression(decl) && ts.isBinaryExpression(decl.parent)) { - return getJSInitializerType(decl, symbol, ts.getAssignedJavascriptInitializer(ts.isBinaryExpression(decl) ? decl.left : decl)) || - getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else if (ts.isParameter(decl) - || ts.isPropertyDeclaration(decl) - || ts.isPropertySignature(decl) - || ts.isVariableDeclaration(decl) - || ts.isBindingElement(decl)) { - // Use type from type annotation if one is present - var isOptional = ts.isParameter(decl) && isJSDocOptionalParameter(decl) || - !ts.isBindingElement(decl) && !ts.isVariableDeclaration(decl) && !!decl.questionToken; - var declaredType = tryGetTypeFromEffectiveTypeNode(decl); - return declaredType && addOptionality(declaredType, isOptional) || - getJSInitializerType(decl, symbol, ts.getDeclaredJavascriptInitializer(decl)) || - getWidenedTypeForVariableLikeDeclaration(decl, /*includeOptionality*/ true); - } - } - function getJSInitializerType(decl, symbol, init) { - if (init && ts.isInJavaScriptFile(init) && ts.isObjectLiteralExpression(init)) { - var exports_1 = ts.createSymbolTable(); - while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { - var s_1 = getSymbolOfNode(decl); - if (s_1 && ts.hasEntries(s_1.exports)) { - mergeSymbolTable(exports_1, s_1.exports); - } - decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; - } - var s = getSymbolOfNode(decl); - if (s && ts.hasEntries(s.exports)) { - mergeSymbolTable(exports_1, s.exports); - } - return createAnonymousType(symbol, exports_1, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + return type; } - function getAnnotatedAccessorType(accessor) { + function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { if (accessor.kind === 156 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); - return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + return getterTypeAnnotation; } else { var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + return setterTypeAnnotation; } } return undefined; } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } function getAnnotatedAccessorThisParameter(accessor) { var parameter = getAccessorThisParameter(accessor); return parameter && parameter.symbol; @@ -33689,60 +34132,60 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; } - var type = void 0; - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; } else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); } + // Otherwise, fall back to 'any'. else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } - type = anyType; } + type = anyType; } } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); - } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } - links.type = type; } - return links.type; + return type; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -33750,6 +34193,7 @@ var ts; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); + var originalLinks = links; if (!links.type) { var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); if (jsDeclaration) { @@ -33768,32 +34212,45 @@ var ts; } } } - if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else if (symbol.valueDeclaration.kind === 202 /* BinaryExpression */ || - symbol.valueDeclaration.kind === 187 /* PropertyAccessExpression */ && symbol.valueDeclaration.parent.kind === 202 /* BinaryExpression */) { - links.type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - var type = createObjectType(16 /* Anonymous */, symbol); - if (symbol.flags & 32 /* Class */) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 202 /* BinaryExpression */ || + declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { + return getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; } - else { - links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); } + return type_1; } } - return links.type; + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } } function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); } function getTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); @@ -33819,7 +34276,7 @@ var ts; } else { if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type = errorType; } symbolInstantiationDepth++; var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); @@ -33923,8 +34380,8 @@ var ts; case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: case 240 /* TypeAliasDeclaration */: - case 300 /* JSDocTemplateTag */: - case 301 /* JSDocTypedefTag */: + case 301 /* JSDocTemplateTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: case 179 /* MappedType */: case 173 /* ConditionalType */: @@ -33987,15 +34444,18 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return false; + return isJavascriptConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + var isJavascript = ts.isInJavaScriptFile(location); + if (isJavascriptConstructorType(type) && !typeArgCount) { + return getSignaturesOfType(type, 0 /* Call */); + } + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); @@ -34082,6 +34542,9 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } + else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere @@ -34416,7 +34879,8 @@ var ts; } /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ function isThislessTypeParameter(node) { - return !node.constraint || isThislessType(node.constraint); + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); } /** * A variable-like declaration is free of this references if it has a type annotation @@ -34514,6 +34978,11 @@ var ts; && ts.isEntityNameExpression(node.expression) && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } /** * Indicates whether a declaration has a late-bindable dynamic name. */ @@ -34951,7 +35420,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_4 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -34974,7 +35443,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_4(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35078,7 +35547,7 @@ var ts; // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), /*_index*/ undefined, prop); + addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -35096,7 +35565,7 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - function addMemberForKeyType(t, _index, origin) { + function addMemberForKeyType(t) { // 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. @@ -35118,9 +35587,9 @@ var ts; prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : propType; - if (origin) { - prop.syntheticOrigin = origin; - prop.declarations = origin.declarations; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; } prop.nameType = t; members.set(propName, prop); @@ -35148,7 +35617,7 @@ var ts; errorType); } function getConstraintDeclarationForMappedType(type) { - return type.declaration.typeParameter.constraint; + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 @@ -35276,11 +35745,7 @@ var ts; return obj.properties.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - if (expected && typeIsLiteralType(expected)) { - var actual = getTypeOfNode(property); - return !!actual && !isTypeIdenticalTo(actual, expected); - } - return false; + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -35389,20 +35854,12 @@ var ts; } return undefined; } - function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { + function getBaseConstraintOfType(type) { if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - } - function getBaseConstraintOfType(type) { - var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); - if (!constraint && type.flags & 1048576 /* Index */) { - return keyofConstraintType; - } - return constraint; + return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35420,23 +35877,24 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var circular; - if (!type.resolvedBaseConstraint) { - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + var result = computeBaseConstraint(getSimplifiedType(t)); + if (!popTypeResolution()) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; } - return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { - circular = true; - return undefined; - } - var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { - circular = true; - return undefined; - } - return result; + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { if (t.flags & 65536 /* TypeParameter */) { @@ -35449,8 +35907,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_3 = types_4[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_4[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -35545,6 +36003,7 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; + var indexTypes; var isUnion = containingType.flags & 262144 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols @@ -35570,14 +36029,21 @@ var ts; } } else if (isUnion) { - checkFlags |= 16 /* Partial */; + var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); + if (index) { + checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, index.type); + } + else { + checkFlags |= 16 /* Partial */; + } } } } if (!props) { return undefined; } - if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } var declarations; @@ -35609,6 +36075,7 @@ var ts; } propTypes.push(type); } + ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && commonValueDeclaration) { @@ -35779,17 +36246,6 @@ var ts; var isBracketed = node.isBracketed, typeExpression = node.typeExpression; return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; } - function createTypePredicateFromTypePredicateNode(node) { - var parameterName = node.parameterName; - var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { - return createIdentifierTypePredicate(parameterName && parameterName.escapedText, // TODO: GH#18217 - parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); - } - else { - return createThisTypePredicate(type); - } - } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; } @@ -35865,7 +36321,7 @@ var ts; var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } - if (i === 0 && paramSymbol.escapedName === "this") { + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { hasThisParameter = true; thisParameter = param.symbol; } @@ -35899,9 +36355,9 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -35929,26 +36385,14 @@ var ts; parameters.push(syntheticArgsSymbol); return true; } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 - } - else if (classType) { - return classType; - } - var typeNode = ts.getEffectiveReturnTypeNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); - } - // TypeScript 1.0 spec (April 2014): - // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); } function containsArgumentsReference(declaration) { var links = getNodeLinks(declaration); @@ -36028,52 +36472,105 @@ var ts; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJavaScriptFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type) : - noTypePredicate; + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 71 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + type = anyType; } signature.resolvedReturnType = type; } return signature.resolvedReturnType; } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 155 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } function isResolvingReturnTypeOfSignature(signature) { return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */) || anyType; + return type && getIndexTypeOfType(type, 1 /* Number */); } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36173,7 +36670,7 @@ var ts; } function getConstraintDeclaration(type) { var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); - return decl && decl.constraint; + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { var inferences; @@ -36219,6 +36716,7 @@ var ts; } return inferences && getIntersectionType(inferences); } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { if (typeParameter.target) { @@ -36234,7 +36732,9 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */).parent); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); } function getTypeListId(types) { var result = ""; @@ -36424,6 +36924,10 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } + var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag && enumTag.typeExpression) { + return getTypeFromTypeNode(enumTag.typeExpression); + } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -36473,7 +36977,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 162 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -36564,7 +37068,7 @@ var ts; // The expression is processed as an identifier expression (section 4.3) // or property access expression(section 4.10), // the widened type(section 3.9) of which becomes the result. - links.resolvedType = getWidenedType(checkExpression(node.exprName)); + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); } return links.resolvedType; } @@ -36683,6 +37187,9 @@ var ts; function createArrayType(elementType) { return createTypeFromGenericGlobalType(globalArrayType, [elementType]); } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -36781,6 +37288,14 @@ var ts; function containsType(types, type) { return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } // Return true if the given intersection type contains // more than one unit type or, // an object type and a nullable type (null or undefined), or @@ -36944,7 +37459,7 @@ var ts; includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, includes & 16749629 /* NotUnit */ ? 0 : 67108864 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37059,29 +37574,65 @@ var ts; } } } - // When intersecting unions of unit types we can simply intersect based on type identity. - // Here we remove all unions of unit types from the given list and replace them with a - // a single union containing an intersection of the unit types. - function intersectUnionsOfUnitTypes(types) { - var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfUnitTypes */) !== 0; }); - var unionType = types[unionIndex]; - var intersection = unionType.types; - var i = types.length - 1; - var _loop_6 = function () { + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 64 /* StringLiteral */ ? stringType : + type.flags & 128 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfUnitTypes */) { - intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } - i--; - }; - while (i > unionIndex) { - _loop_6(); + else { + i++; + } } - if (intersection === unionType.types) { + // Return false if there was only one union of primitive types + if (!unionTypes) { return false; } - types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 67108864 /* UnionOfUnitTypes */); + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -37121,7 +37672,7 @@ var ts; return typeSet[0]; } if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -37232,6 +37783,33 @@ var ts; type.indexType = indexType; return type; } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 262144 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 524288 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 15794176 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : @@ -37251,7 +37829,8 @@ var ts; getNodeLinks(accessNode).resolvedSymbol = prop; } } - return getTypeOfSymbol(prop); + var propType = getTypeOfSymbol(prop); + return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; } if (isTupleType(objectType)) { var restType = getRestTypeOfTupleType(objectType); @@ -37261,7 +37840,7 @@ var ts; } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (isTypeAny(objectType)) { + if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { return objectType; } var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || @@ -37280,9 +37859,15 @@ var ts; if (indexType.flags & 32768 /* Never */) { return neverType; } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1 /* Number */)) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); } else { @@ -37300,6 +37885,9 @@ var ts; return anyType; } } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessNode) { var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { @@ -37386,7 +37974,7 @@ var ts; return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 65536 /* TypeParameter */) { - var constraint = getConstraintFromTypeParameter(objectType); + var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); } @@ -37613,19 +38201,17 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var argumentType = getTypeFromTypeNode(node.argument); - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type - var moduleName = argumentType.value; - var innerModuleSymbol = resolveExternalModule(node, moduleName, ts.Diagnostics.Cannot_find_module_0, node, /*isForAugmentation*/ false); + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var moduleSymbol_1 = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); - var currentNamespace = moduleSymbol_1; + var currentNamespace = moduleSymbol; var current = void 0; while (current = nameStack.shift()) { var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; @@ -37641,14 +38227,14 @@ var ts; resolveImportSymbolType(node, links, currentNamespace, targetMeaning); } else { - if (moduleSymbol_1.flags & targetMeaning) { - resolveImportSymbolType(node, links, moduleSymbol_1, targetMeaning); + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { var errorMessage = targetMeaning === 67216319 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; - error(node, errorMessage, moduleName); + error(node, errorMessage, node.argument.literal.text); links.resolvedSymbol = unknownSymbol; links.resolvedType = errorType; } @@ -37734,20 +38320,16 @@ var ts; } for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; - // we approximate own properties as non-methods plus methods that are inside the object literal - var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.escapedName, true); } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + else if (isSpreadableProperty(rightProp)) { members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { var leftProp = _c[_b]; - if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) - || skippedPrivateMembers.has(leftProp.escapedName) - || isClassMethod(leftProp)) { + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { continue; } if (members.has(leftProp.escapedName)) { @@ -37774,6 +38356,12 @@ var ts; spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) + ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) + : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { return prop; @@ -37792,9 +38380,6 @@ var ts; } return index; } - function isClassMethod(prop) { - return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } function createLiteralType(flags, value, symbol) { var type = createType(flags); type.symbol = symbol; @@ -37954,7 +38539,7 @@ var ts; case 71 /* Identifier */: case 146 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: return errorType; } @@ -38130,7 +38715,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavaScriptConstructor(declaration_1)) { + if (isJavascriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38190,11 +38775,16 @@ var ts; } } 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 - // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated - // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for - // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a - // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & 1048576 /* Index */) { var typeVariable_1 = constraintType.type; @@ -38203,7 +38793,11 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); + var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); } return t; }); @@ -38215,6 +38809,25 @@ var ts; function isMappableType(type) { return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + propType; + } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { @@ -38366,6 +38979,9 @@ var ts; return true; } } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); @@ -38377,7 +38993,7 @@ var ts; function getTypeWithoutSignatures(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { + if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; @@ -38517,8 +39133,8 @@ var ts; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } - if (!issuedElaboration && (ts.length(targetProp && targetProp.declarations) || ts.length(target.symbol && target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); } } reportedError = true; @@ -38667,9 +39283,9 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceRestTypeParameter = getRestTypeParameter(source); - var targetRestTypeParameter = sourceRestTypeParameter ? getRestTypeParameter(target) : undefined; - if (sourceRestTypeParameter && !(targetRestTypeParameter && sourceCount === targetCount)) { + var sourceGenericRestType = getGenericRestType(source); + var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; + if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -38695,8 +39311,8 @@ var ts; var paramCount = Math.max(sourceCount, targetCount); var lastIndex = paramCount - 1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceRestTypeParameter || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetRestTypeParameter || getTypeAtPosition(target, i); + var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); + var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -38722,11 +39338,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? + getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? + getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39231,6 +39849,9 @@ var ts; return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && @@ -39241,7 +39862,7 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_7 = function (prop) { + var _loop_5 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -39280,9 +39901,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_7(prop); - if (typeof state_3 === "object") - return state_3.value; + var state_2 = _loop_5(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -39314,7 +39935,8 @@ var ts; } if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || - findMatchingTypeReferenceOrTypeAliasReference(source, target); + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39336,6 +39958,11 @@ var ts; }); } } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -39935,8 +40562,12 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); + var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { // An abstract constructor type is not assignable to a non-abstract constructor type @@ -40186,7 +40817,7 @@ var ts; return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -40448,6 +41079,9 @@ var ts; function isArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray @@ -40630,7 +41264,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; - regularNew.objectFlags |= 128 /* ObjectLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; } @@ -40708,7 +41342,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); - return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); @@ -40840,13 +41476,13 @@ var ts; sourceHasRest ? targetCount : targetHasRest ? sourceCount : Math.min(sourceCount, targetCount); - var targetRestTypeVariable = getRestTypeParameter(target); - var paramCount = targetRestTypeVariable ? Math.min(targetCount - 1, maxCount) : maxCount; + var targetGenericRestType = getGenericRestType(target); + var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetRestTypeVariable) { - callback(getRestTypeAtPosition(source, paramCount), targetRestTypeVariable); + if (targetGenericRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -40958,6 +41594,22 @@ var ts; return undefined; } } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; @@ -41522,7 +42174,7 @@ var ts; case 71 /* Identifier */: return ts.idText(name); case 147 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; @@ -41546,8 +42198,9 @@ var ts; case 97 /* SuperKeyword */: return target.kind === 97 /* SuperKeyword */; case 187 /* PropertyAccessExpression */: - return target.kind === 187 /* PropertyAccessExpression */ && - source.name.escapedText === target.name.escapedText && + case 188 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); case 184 /* BindingElement */: if (target.kind !== 187 /* PropertyAccessExpression */) @@ -41565,6 +42218,11 @@ var ts; } return false; } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } function containsMatchingReference(source, target) { while (source.kind === 187 /* PropertyAccessExpression */) { source = source.expression; @@ -41644,18 +42302,6 @@ var ts; } return flow.id; } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 262144 /* Union */)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -41664,7 +42310,7 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); if (!(reducedType.flags & 32768 /* Never */)) { return reducedType; } @@ -41920,7 +42566,7 @@ var ts; if (type.flags & 262144 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfUnitTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); } return f(type) ? type : neverType; } @@ -42162,7 +42808,10 @@ var ts; 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 !== 187 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + if (container && container !== flowContainer && + reference.kind !== 187 /* PropertyAccessExpression */ && + reference.kind !== 188 /* ElementAccessExpression */ && + reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -42391,13 +43040,22 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 187 /* PropertyAccessExpression */ && - computedType.flags & 262144 /* Union */ && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(computedType, expr.name.escapedText); + if (!(computedType.flags & 262144 /* Union */) || + expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.escapedText; + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); @@ -42681,6 +43339,7 @@ var ts; case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); case 189 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); @@ -42897,6 +43556,7 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -42908,7 +43568,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || node.parent.kind === 211 /* NonNullExpression */ || @@ -43071,15 +43731,14 @@ var ts; // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); - var needToCaptureLexicalThis = false; + var capturedByArrowFunction = false; if (container.kind === 155 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. if (container.kind === 195 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); - // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); + capturedByArrowFunction = true; } switch (container.kind) { case 242 /* ModuleDeclaration */: @@ -43107,13 +43766,16 @@ var ts; error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } - if (needToCaptureLexicalThis) { + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { captureLexicalThis(node, container); } var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); } return type || anyType; } @@ -43122,8 +43784,8 @@ var ts; if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. Check if it's the RHS - // of a x.prototype.y = function [name]() { .... } + // If this is a function in a JS file, it might be a class method. + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } if (container.kind === 194 /* FunctionExpression */ && container.parent.kind === 202 /* BinaryExpression */ && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { @@ -43137,6 +43799,17 @@ var ts; return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); } } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJavascriptClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return getFlowTypeOfReference(node, thisType); @@ -43160,7 +43833,7 @@ var ts; var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && - jsDocFunctionType.parameters[0].name.escapedText === "this") { + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } @@ -43449,20 +44122,10 @@ var ts; } var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameter = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameter ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - // If last parameter is contextually rest parameter get its type - if (funcHasRestParameter && indexOfParameter === len) { - return getRestTypeAtPosition(contextualSignature, indexOfParameter); - } + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); } } // In a variable, parameter or property declaration with a type annotation, @@ -43548,10 +44211,9 @@ var ts; function getContextualReturnType(functionDecl) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.kind === 155 /* Constructor */ || - ts.getEffectiveReturnTypeNode(functionDecl) || - isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature @@ -43600,22 +44262,39 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments to avoid circularity. + // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function isContextSensitiveAssignment(binaryExpression) { var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); switch (kind) { case 0 /* None */: return true; case 5 /* Property */: - // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. - // See `bindStaticPropertyAssignment` in `binder.ts`. - return !binaryExpression.left.symbol; case 1 /* ExportsProperty */: - case 2 /* ModuleExports */: + case 6 /* Prototype */: case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + if (ts.isInJavaScriptFile(decl)) { + return !!ts.getJSDocTypeTag(decl); + } + else if (ts.isIdentifier(binaryExpression.left.expression)) { + var id = binaryExpression.left.expression; + var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); + return !ts.isFunctionSymbol(parentSymbol); + } + return true; + } case 4 /* ThisProperty */: - case 6 /* Prototype */: - return false; + case 2 /* ModuleExports */: + return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); default: return ts.Debug.assertNever(kind); } @@ -44030,16 +44709,11 @@ var ts; // union type of return types from these signatures function getContextualSignature(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type; - if (ts.isInJavaScriptFile(node)) { - var jsdoc = ts.getJSDocType(node); - if (jsdoc) { - type = getTypeFromTypeNode(jsdoc); - } - } - if (!type) { - type = getContextualTypeForFunctionLikeDeclaration(node); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; } + var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } @@ -44247,7 +44921,8 @@ var ts; var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); - var isJSObjectLiteral = !contextualType && isInJSFile; + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44271,6 +44946,9 @@ var ts; checkTypeAssignableTo(type, jsDocType, memberDecl); type = jsDocType; } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } } typeFlags |= type.flags; var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? @@ -44380,12 +45058,15 @@ var ts; } return createObjectLiteralType(); function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); result.objectFlags |= 128 /* ObjectLiteral */; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } @@ -44772,7 +45453,7 @@ var ts; var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); @@ -44808,7 +45489,7 @@ var ts; if (jsxStatelessElementType) { // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); var result = void 0; var allMatchingAttributesType = void 0; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { @@ -45116,6 +45797,10 @@ var ts; } } } + else if (targetType.flags & 4194304 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } return false; } /** @@ -45173,11 +45858,6 @@ var ts; return errorType; } } - // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized - // '.prototype' property as well as synthesized tuple index properties. - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 152 /* PropertyDeclaration */; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } @@ -45199,23 +45879,19 @@ var ts; * Check whether the requested property access is valid. * Returns true if node is a valid property access, and false otherwise. * @param node The node to be checked. - * @param left The left hand side of the property access (e.g.: the super in `super.foo`). - * @param type The type of left. - * @param prop The symbol for the right hand side of the property access. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, left, type, prop) { + function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 187 /* PropertyAccessExpression */ || node.kind === 235 /* VariableDeclaration */ ? - node.name : - node.kind === 181 /* ImportType */ ? - node : - node.right; + var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or // instance member variable initializer where this references a derived class instance, @@ -45262,7 +45938,7 @@ var ts; } // Property is known to be protected at this point // All protected properties of a supertype are accessible in a super access - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { return true; } // Find the first enclosing class that has the declaring classes of the protected constituents @@ -45281,7 +45957,7 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintFromTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { @@ -45302,10 +45978,7 @@ var ts; return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; } function symbolHasNonMethodDeclaration(symbol) { - return forEachProperty(symbol, function (prop) { - var propKind = getDeclarationKindFromSymbol(prop); - return propKind !== 154 /* MethodDeclaration */ && propKind !== 153 /* MethodSignature */; - }); + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); @@ -45351,6 +46024,9 @@ var ts; if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } @@ -45365,7 +46041,7 @@ var ts; checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); @@ -45423,7 +46099,7 @@ var ts; diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializer(node) { @@ -45468,6 +46144,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; + var relatedInfo; if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; @@ -45477,32 +46154,44 @@ var ts; } } } - var promisedType = getPromisedTypeOfPromise(containingType); - if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - 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), suggestion); + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion_1 = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion_1 !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion_1); + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { - var suggestion = getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); @@ -45512,10 +46201,17 @@ var ts; // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - return result && ts.symbolName(result); + return result; + } + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); } - function getSuggestionForNonexistentModule(name, targetModule) { - var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); return suggestion && ts.symbolName(suggestion); } /** @@ -45559,15 +46255,15 @@ var ts; function isValidPropertyAccess(node, propertyName) { switch (node.kind) { case 187 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression, propertyName, getWidenedType(checkExpression(node.expression))); + return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); case 146 /* QualifiedName */: - return isValidPropertyAccessWithType(node, node.left, propertyName, getWidenedType(checkExpression(node.left))); + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); case 181 /* ImportType */: - return isValidPropertyAccessWithType(node, node, propertyName, getTypeFromTypeNode(node)); + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 181 /* ImportType */ ? node : node.expression, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -45587,14 +46283,14 @@ var ts; inferTypes(context.inferences, actualThisType, signatureThisType); return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); } - function isValidPropertyAccessWithType(node, left, propertyName, type) { + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { if (type === errorType || isTypeAny(type)) { return true; } var prop = getPropertyOfType(type, propertyName); - return prop ? checkPropertyAccessibility(node, left, type, prop) + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -45790,7 +46486,6 @@ var ts; function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call - var typeArguments; // Type arguments (undefined if none) var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { @@ -45801,7 +46496,6 @@ var ts; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = node.typeArguments; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. @@ -45818,7 +46512,6 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { @@ -45830,12 +46523,8 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } - if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { - return false; - } // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. if (spreadArgIndex >= 0) { return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); @@ -45939,8 +46628,8 @@ var ts; // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var restTypeParameter = getRestTypeParameter(signature); - var argCount = restTypeParameter ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var genericRestType = getGenericRestType(signature); + var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. @@ -45958,9 +46647,9 @@ var ts; inferTypes(context.inferences, argType, paramType); } } - if (restTypeParameter) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, restTypeParameter, context); - inferTypes(context.inferences, spreadType, restTypeParameter); + if (genericRestType) { + var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); + inferTypes(context.inferences, spreadType, genericRestType); } // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed @@ -46356,7 +47045,7 @@ var ts; node.kind === 157 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - var propertyType = getTypeOfNode(node); // TODO: GH#18217 + var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); @@ -46422,18 +47111,54 @@ var ts; return arg; } } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + min = Math.min(min, minCount); + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } var paramCount = min === max ? min : min + "-" + max; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; var isDecorator = node.kind === 150 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -46505,11 +47230,12 @@ var ts; // foo(0); // var candidateForArgumentError; + var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -46545,73 +47271,30 @@ var ts; // an error, we don't need to exclude any arguments, although it would cause no harm to do so. checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { - var min_1 = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; - min_1 = Math.min(min_1, getMinArgumentCount(sig)); - max = Math.max(max, getParameterCount(sig)); - } - var hasRestParameter_1 = ts.some(signatures, hasEffectiveRestParameter); - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - var paramCount = hasRestParameter_1 ? min_1 : - min_1 < max ? min_1 + "-" + max : - min_1; - var argCount = args.length; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - ts.Diagnostics.Expected_0_arguments_but_got_1; - diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + diagnostics.add(getArgumentArityError(node, signatures, args)); } else if (fallbackError) { diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } - // No signature was applicable. We have already reported the errors for the invalid signature. - // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. - // Pick the longest signature. This way we can get a contextual type for cases like: - // declare function f(a: { xa: number; xb: number; }, b: number); - // f({ | - // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: - // declare function f(k: keyof T); - // f(" - if (!produceDiagnostics) { - ts.Debug.assert(candidates.length > 0); // Else would have exited above. - var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); - var candidate = candidates[bestIndex]; - var typeParameters = candidate.typeParameters; - if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); // TODO: GH#18217 - while (typeArguments_1.length > typeParameters.length) { - typeArguments_1.pop(); - } - while (typeArguments_1.length < typeParameters.length) { - typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); - } - var instantiated = createSignatureInstantiation(candidate, typeArguments_1); - candidates[bestIndex] = instantiated; - return instantiated; - } - return candidate; - } - return resolveErrorCall(node); + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -46622,7 +47305,7 @@ var ts; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; @@ -46648,6 +47331,12 @@ var ts; } var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = candidate; + break; + } } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; @@ -46669,6 +47358,87 @@ var ts; return undefined; } } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_6 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_6(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments); + candidates[bestIndex] = instantiated; + return instantiated; + } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; var maxParams = -1; @@ -46685,11 +47455,14 @@ var ts; } return maxParamsIndex; } - function resolveCallExpression(node, candidatesOutArray) { + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { - ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } return anySignature; } if (superType !== errorType) { @@ -46698,7 +47471,7 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); } } return resolveUntypedCall(node); @@ -46741,7 +47514,12 @@ var ts; } return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * TS 1.0 spec: 4.12 @@ -46753,7 +47531,7 @@ var ts; return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } - function resolveNewExpression(node, candidatesOutArray) { + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { @@ -46801,7 +47579,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray); + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -46809,8 +47587,8 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } if (getThisTypeOfSignature(signature) === voidType) { @@ -46821,6 +47599,38 @@ var ts; invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 524288 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } function isConstructorAccessible(node, signature) { if (!signature || !signature.declaration) { return true; @@ -46836,16 +47646,10 @@ var ts; // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); - if (containingClass) { + if (containingClass && modifiers & 16 /* Protected */) { var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; } } if (modifiers & 8 /* Private */) { @@ -46877,7 +47681,7 @@ var ts; addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); if (apparentType === errorType) { @@ -46893,7 +47697,7 @@ var ts; invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -46918,7 +47722,7 @@ var ts; /** * Resolves a decorator as if it were a call expression. */ - function resolveDecorator(node, candidatesOutArray) { + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); if (apparentType === errorType) { @@ -46943,7 +47747,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -46967,30 +47771,30 @@ var ts; * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; * the function will fill it up with appropriate candidate signatures */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); } return undefined; } - function resolveSignature(node, candidatesOutArray) { + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { case 189 /* CallExpression */: - return resolveCallExpression(node, candidatesOutArray); + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); case 190 /* NewExpression */: - return resolveNewExpression(node, candidatesOutArray); + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); case 191 /* TaggedTemplateExpression */: - return resolveTaggedTemplateExpression(node, candidatesOutArray); + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); case 150 /* Decorator */: - return resolveDecorator(node, candidatesOutArray); + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); case 260 /* JsxOpeningElement */: case 259 /* JsxSelfClosingElement */: // This code-path is called by language service var exprTypes = checkExpression(node.tagName); return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); if (sfcResult && sfcResult !== unknownSignature) { return sfcResult; } @@ -47010,7 +47814,8 @@ var ts; * the function will fill it up with appropriate candidate signatures * @return a signature of the call-like expression or undefined if one can't be found */ - function getResolvedSignature(node, candidatesOutArray) { + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } var links = getNodeLinks(node); // If getResolvedSignature has already been called, we will have cached the resolvedSignature. // However, it is possible that either candidatesOutArray was not passed in the first time, @@ -47021,7 +47826,7 @@ var ts; return cached; } links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); // If signature resolution originated in control flow type analysis (for example to compute the // assigned type in a flow assignment) we don't cache the result as it may be based on temporary // types from the control flow analysis. @@ -47032,7 +47837,7 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavaScriptConstructor(node) { + function isJavascriptConstructor(node) { if (node && ts.isInJavaScriptFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) @@ -47045,14 +47850,21 @@ var ts; } return false; } - function getJavaScriptClassType(symbol) { + function isJavascriptConstructorType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJavascriptClassType(symbol) { var inferred; - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47125,7 +47937,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavaScriptClassType(funcSymbol); + var type = funcSymbol && getJavascriptClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47151,7 +47963,8 @@ var ts; if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { - jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; } } } @@ -47268,7 +48081,7 @@ var ts; if (produceDiagnostics && targetType !== errorType) { var widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); } } return targetType; @@ -47335,6 +48148,9 @@ var ts; return restParameter.escapedName; } function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); @@ -47345,22 +48161,19 @@ var ts; if (pos - paramCount < getLengthOfTupleType(restType)) { return restType.typeArguments[pos - paramCount]; } - var tupleRestType = getRestTypeOfTupleType(restType); - if (tupleRestType) { - return tupleRestType; - } + return getRestTypeOfTupleType(restType); } - return getIndexTypeOfType(restType, 1 /* Number */) || anyType; + return getIndexTypeOfType(restType, 1 /* Number */); } - return anyType; + return undefined; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); var hasRest = hasEffectiveRestParameter(source); if (hasRest && pos === paramCount - 1) { - var restTypeVariable = getRestTypeParameter(source); - if (restTypeVariable) { - return restTypeVariable; + var genericRestType = getGenericRestType(source); + if (genericRestType) { + return genericRestType; } } var start = hasRest ? Math.min(pos, paramCount - 1) : pos; @@ -47406,10 +48219,10 @@ var ts; } return signature.minArgumentCount; } - function getRestTypeParameter(signature) { + function getGenericRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 65536 /* TypeParameter */) { + if (restType.flags & 15794176 /* Instantiable */) { return restType; } } @@ -47677,7 +48490,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -47708,7 +48521,7 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 3 /* AnyOrUnknown */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. @@ -47749,6 +48562,16 @@ var ts; ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + } return anyFunctionType; } // Grammar checking @@ -47780,7 +48603,7 @@ var ts; contextualSignature : instantiateSignature(contextualSignature, contextualMapper); assignContextualParameterTypes(signature, instantiatedContextualSignature); } - if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, checkMode); if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; @@ -47793,20 +48616,21 @@ var ts; } return type; } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - var returnOrPromisedType = returnTypeNode && - ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : // Async function - getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { - if (!returnTypeNode) { + if (!ts.getEffectiveReturnTypeNode(node)) { // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors // we need. An example is the noImplicitAny errors resulting from widening the return expression // of a function. Because checking of function expression bodies is deferred, there was never an @@ -47870,7 +48694,7 @@ var ts; // If func.parent is a class and symbol is a (readonly) property of that class, or // if func is a constructor and symbol is a (readonly) parameter property declared in it, // then symbol is writeable here. - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -47956,6 +48780,7 @@ var ts; } return numberType; case 51 /* ExclamationToken */: + checkTruthinessExpression(node.operand); var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); return facts === 1048576 /* Truthy */ ? falseType : facts === 2097152 /* Falsy */ ? trueType : @@ -48065,19 +48890,20 @@ var ts; } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType) { + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { var properties = node.properties; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; } /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { var name = property.name; if (name.kind === 147 /* ComputedPropertyName */) { @@ -48086,20 +48912,10 @@ var ts; if (isComputedNonLiteralName(name)) { return undefined; } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || - getIndexTypeOfType(objectLiteralType, 0 /* String */); + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { - if (property.kind === 274 /* ShorthandPropertyAssignment */) { - return checkDestructuringAssignment(property, type); - } - else { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.initializer, type); - } + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); @@ -48123,6 +48939,23 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -48180,7 +49013,7 @@ var ts; } return undefined; } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; @@ -48203,7 +49036,7 @@ var ts; target = target.left; } if (target.kind === 186 /* ObjectLiteralExpression */) { - return checkObjectLiteralAssignment(target, sourceType); + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } if (target.kind === 185 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); @@ -48293,9 +49126,15 @@ var ts; function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + } + var leftType; + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); } - var leftType = checkExpression(left, checkMode); var rightType = checkExpression(right, checkMode); switch (operator) { case 39 /* AsteriskToken */: @@ -48417,7 +49256,7 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.getSpecialPropertyAssignmentKind(left.parent); + var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; checkSpecialAssignment(special, right); if (isJSSpecialPropertyAssignment(special)) { return leftType; @@ -48497,8 +49336,9 @@ var ts; } function isJSSpecialPropertyAssignment(special) { switch (special) { - case 1 /* ExportsProperty */: case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: case 5 /* Property */: case 6 /* Prototype */: case 3 /* PrototypeProperty */: @@ -48582,16 +49422,16 @@ var ts; // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. - var returnType = ts.getEffectiveReturnTypeNode(func); + var returnType = getReturnTypeFromAnnotation(func); if (returnType) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); } // Both yield and yield* expressions have type 'any' return anyType; } function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); + checkTruthinessExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -48604,7 +49444,7 @@ var ts; // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { - error(templateSpan.expression, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1, typeToString(esSymbolType), typeToString(stringType)); + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; @@ -48774,9 +49614,6 @@ var ts; node.contextualType = saveContextualType; return type; } - function checkExpresionNoReturn(node) { - checkExpression(node); - } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -48919,7 +49756,7 @@ var ts; checkSourceElement(node.default); var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } if (!hasNonCircularTypeParameterDefault(typeParameter)) { error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); @@ -48959,6 +49796,9 @@ var ts; if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } + if (func.kind === 195 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. @@ -48966,17 +49806,6 @@ var ts; error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - } - return -1; - } function checkTypePredicate(node) { var parent = getTypePredicateParent(node); if (!parent) { @@ -49000,8 +49829,7 @@ var ts; } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), // TODO: GH#18217 - node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -49122,7 +49950,7 @@ var ts; } } else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node); + checkAsyncFunctionReturnType(node, returnTypeNode); } } if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { @@ -49577,7 +50405,10 @@ var ts; } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, keyofConstraintType, node.typeParameter.constraint); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); } function checkTypeOperator(node) { checkGrammarTypeOperatorNode(node); @@ -49591,6 +50422,7 @@ var ts; grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); } function checkImportType(node) { checkSourceElement(node.argument); @@ -49878,7 +50710,7 @@ var ts; case 239 /* InterfaceDeclaration */: case 240 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return 2 /* ExportType */; case 242 /* ModuleDeclaration */: @@ -50077,16 +50909,15 @@ var ts; * Checks the return type of an async function to ensure it is a compatible * Promise implementation. * - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. * * @param node The signature to check */ - function checkAsyncFunctionReturnType(node) { + function checkAsyncFunctionReturnType(node, returnTypeNode) { // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -50111,30 +50942,29 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); // TODO: GH#18217 var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (returnType === errorType) { - return errorType; + return; } var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return errorType; + return; } } else { // Always mark the type node as referenced if it points to a value markTypeNodeAsReferenced(returnTypeNode); if (returnType === errorType) { - return errorType; + return; } var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === undefined) { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return errorType; + return; } var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; @@ -50145,28 +50975,27 @@ var ts; else { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); } - return errorType; + return; } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return errorType; + return; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } } - // Get and return the awaited type of the return type. - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } /** Check a decorator */ function checkDecorator(node) { @@ -50197,7 +51026,7 @@ var ts; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); // TODO: GH#18217 + var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; @@ -50321,9 +51150,13 @@ var ts; } } break; - case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: + var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 154 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); @@ -50363,6 +51196,13 @@ var ts; } checkSourceElement(node.typeExpression); } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } @@ -50457,14 +51297,11 @@ var ts; } var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function - var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ - ? checkAsyncFunctionReturnType(node) // Async function - : getTypeFromTypeNode(returnTypeNode)); // normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } - if (produceDiagnostics && !returnTypeNode) { + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { @@ -50477,6 +51314,13 @@ var ts; getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJavaScriptFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. @@ -50531,6 +51375,7 @@ var ts; case 163 /* FunctionType */: case 164 /* ConstructorType */: case 240 /* TypeAliasDeclaration */: + case 174 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -50541,7 +51386,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; @@ -50561,14 +51406,14 @@ var ts; } var symbol = getSymbolOfNode(member); if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; case 155 /* 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 */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } } break; @@ -50585,16 +51430,45 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { + if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + return; + if (node.kind === 174 /* InferType */) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + else { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; - if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol))); + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } function addToGroup(map, key, value, getKey) { var keyString = String(getKey(key)); var group = map.get(keyString); @@ -50645,7 +51519,7 @@ var ts; var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); if (parameter && name) { if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { @@ -50662,7 +51536,7 @@ var ts; (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { - addDiagnostic(0 /* Local */, unuseds.length === 1 + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); } @@ -50681,29 +51555,29 @@ var ts; addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - addDiagnostic(kind, bindingElements.length === 1 - ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); } } else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; - addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); } } }); unusedVariables.forEach(function (_a) { var declarationList = _a[0], declarations = _a[1]; if (declarationList.declarations.length === declarations.length) { - addDiagnostic(0 /* Local */, declarations.length === 1 + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var decl = declarations_5[_i]; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); } } }); @@ -51006,10 +51880,13 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + } } } } @@ -51130,7 +52007,7 @@ var ts; function checkIfStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); if (node.thenStatement.kind === 218 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); @@ -51141,14 +52018,21 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); checkSourceElement(node.statement); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); } function checkWhileStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.statement); } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 4096 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { @@ -51165,7 +52049,7 @@ var ts; } } if (node.condition) - checkExpression(node.condition); + checkTruthinessExpression(node.condition); if (node.incrementor) checkExpression(node.incrementor); checkSourceElement(node.statement); @@ -51569,10 +52453,6 @@ var ts; checkGrammarBreakOrContinueStatement(node); // TODO: Check that target label is valid } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 156 /* GetAccessor */ - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 157 /* SetAccessor */)) !== undefined; - } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function @@ -51612,7 +52492,7 @@ var ts; error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + else if (getReturnTypeFromAnnotation(func)) { if (functionFlags & 2 /* Async */) { // Async function var promisedType = getPromisedTypeOfPromise(returnType); var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -51921,8 +52801,9 @@ var ts; } // If the type parameter node does not have an identical constraint as the resolved // type parameter at this position, we report an error. - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); if (sourceConstraint) { // relax check if later interface augmentation has no constraint if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { @@ -52018,8 +52899,9 @@ var ts; // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52062,7 +52944,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_7 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52081,7 +52963,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_7(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -52841,9 +53723,9 @@ var ts; } else { // export * from "foo" - var moduleSymbol_2 = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol_2 && hasExportAssignmentSymbol(moduleSymbol_2)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol_2)); + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + 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 && moduleKind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768 /* ExportStar */); @@ -52934,9 +53816,9 @@ var ts; } } // Checks for export * conflicts - var exports_2 = getExportsOfModule(moduleSymbol); - if (exports_2) { - exports_2.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -53036,6 +53918,8 @@ var ts; case 169 /* OptionalType */: case 170 /* RestType */: return checkSourceElement(node.type); + case 176 /* ThisType */: + return checkThisType(node); case 177 /* TypeOperator */: return checkTypeOperator(node); case 173 /* ConditionalType */: @@ -53046,12 +53930,14 @@ var ts; return checkImportType(node); case 293 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 299 /* JSDocTypeTag */: + case 301 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 300 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: return checkJSDocParameterTag(node); case 287 /* JSDocFunctionType */: checkSignatureDeclaration(node); @@ -53264,10 +54150,7 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1 /* TypeChecked */)) { - // If skipLibCheck is enabled, skip type checking if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip type checking if file contains a - // '/// ' directive. - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + if (ts.skipTypeChecking(node, compilerOptions)) { return; } // Grammar checking @@ -53281,8 +54164,8 @@ var ts; registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { - if (unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { diagnostics.add(diag); } }); @@ -53361,6 +54244,7 @@ var ts; var symbols = ts.createSymbolTable(); var isStatic = false; populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword return symbolsToArray(symbols); function populateSymbols() { while (location) { @@ -53583,10 +54467,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 296 /* JSDocParameterTag */) { + if (entityName.parent.kind === 297 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 300 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -53655,7 +54539,7 @@ var ts; grandParent.kind === 182 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; } @@ -53739,7 +54623,7 @@ var ts; } if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { var containingClass = ts.getContainingClass(node); var classType = getTypeOfNode(containingClass); typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); @@ -53754,8 +54638,8 @@ var ts; // extends clause of a class. We handle that case here. var classNode = ts.getContainingClass(node); var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -53764,7 +54648,7 @@ var ts; } if (isTypeDeclarationName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } if (ts.isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -53773,10 +54657,10 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); + return symbol ? getTypeOfSymbol(symbol) : errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -54394,7 +55278,8 @@ var ts; setAccessor: setAccessor, getAccessor: getAccessor }; - } + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55505,9 +56390,6 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - if (node.name.kind === 183 /* ArrayBindingPattern */ || node.name.kind === 182 /* ObjectBindingPattern */) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (node.propertyName) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); } @@ -55779,10 +56661,10 @@ var ts; // this has already been reported, and don't report if it has. // if (node.parent.kind === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { - var links_1 = getNodeLinks(node.parent); + var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); } } else { @@ -56914,19 +57796,7 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - 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; - } + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters @@ -57038,17 +57908,7 @@ var ts; return node; } ts.createConditional = createConditional; - 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]; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue @@ -57851,7 +58711,7 @@ var ts; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -57867,7 +58727,7 @@ var ts; function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(260 /* JsxOpeningElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -58162,7 +59022,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(304 /* NotEmittedStatement */); + var node = createSynthesizedNode(305 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -58174,7 +59034,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(308 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -58186,7 +59046,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(307 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -58201,7 +59061,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(305 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -58217,7 +59077,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 306 /* CommaListExpression */) { + if (node.kind === 307 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -58227,7 +59087,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(306 /* CommaListExpression */); + var node = createSynthesizedNode(307 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -59397,6 +60257,11 @@ var ts; var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1 /* LessThan */: @@ -59539,11 +60404,15 @@ var ts; */ function parenthesizeDefaultExpression(e) { var check = ts.skipPartiallyEmittedExpressions(e); - return check.kind === 207 /* ClassExpression */ || - check.kind === 194 /* FunctionExpression */ || - isCommaSequence(check) - ? ts.createParen(e) - : e; + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; } ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; /** @@ -59696,6 +60565,9 @@ var ts; case 203 /* ConditionalExpression */: node = node.condition; continue; + case 191 /* TaggedTemplateExpression */: + node = node.tag; + continue; case 189 /* CallExpression */: if (stopAtCallExpressions) { return node; @@ -59705,7 +60577,7 @@ var ts; case 188 /* ElementAccessExpression */: case 187 /* PropertyAccessExpression */: case 211 /* NonNullExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -59721,7 +60593,7 @@ var ts; ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || - node.kind === 306 /* CommaListExpression */; + node.kind === 307 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -59740,7 +60612,7 @@ var ts; case 210 /* AsExpression */: case 211 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -59777,7 +60649,7 @@ var ts; case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 305 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -60054,7 +60926,7 @@ var ts; // `1` in `let { 1: b } = ...` if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -60066,7 +60938,7 @@ var ts; // `1` in `({ 1: b } = ...)` if (bindingElement.name) { var propertyName = bindingElement.name; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -60077,13 +60949,18 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) ? target.expression : target; } ts.Debug.fail("Invalid property name for binding element."); } ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } /** * Gets the elements of a BindingOrAssignmentPattern */ @@ -60567,9 +61444,9 @@ var ts; case 277 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -60625,7 +61502,7 @@ var ts; case 218 /* EmptyStatement */: case 208 /* OmittedExpression */: case 234 /* DebuggerStatement */: - case 304 /* NotEmittedStatement */: + case 305 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -61004,10 +61881,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -61021,8 +61898,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) - : ts.prependStatements(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -61200,7 +62077,7 @@ var ts; function decode(host, mapPath, map, program, fallbackCache) { if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot || currentDirectory; + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; var decodedMappings; var generatedOrderedMappings; var sourceOrderedMappings; @@ -61235,10 +62112,11 @@ var ts; } function getSourceFileLike(fileName, location) { // Lookup file in program, if provided - var file = program && program.getSourceFile(fileName); - if (!file) { + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + var file = program && program.getSourceFile(path); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (!file || file.resolvedPath !== path) { // Otherwise check the cache (which may hit disk) - var path = ts.toPath(fileName, location, host.getCanonicalFileName); return fallbackCache.get(path); } return file; @@ -62074,7 +62952,7 @@ var ts; var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); return ts.createElementAccess(value, argumentExpression); } - else if (ts.isStringOrNumericLiteral(propertyName)) { + else if (ts.isStringOrNumericLiteralLike(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); @@ -62754,7 +63632,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, context.endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -63206,6 +64084,7 @@ var ts; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); statements.push(statement); } } @@ -63223,6 +64102,7 @@ var ts; ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); expressions.push(expression); } return expressions; @@ -63643,6 +64523,11 @@ var ts; } return false; } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } /** * Serializes the type of a node for use with decorator type metadata. * @@ -63652,10 +64537,10 @@ var ts; switch (node.kind) { case 152 /* PropertyDeclaration */: case 149 /* Parameter */: - case 156 /* GetAccessor */: return serializeTypeNode(node.type); case 157 /* SetAccessor */: - return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 156 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 154 /* MethodDeclaration */: @@ -63846,11 +64731,11 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: - var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); + return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); case ts.TypeReferenceSerializationKind.BooleanType: @@ -63875,14 +64760,35 @@ var ts; return ts.Debug.assertNever(kind); } } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 71 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 71 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } /** * Serializes an entity name as an expression for decorator type metadata. * * @param node The entity name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * entity name at runtime. */ - function serializeEntityNameAsExpression(node, useFallback) { + function serializeEntityNameAsExpression(node) { switch (node.kind) { case 71 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were @@ -63891,12 +64797,9 @@ var ts; name.flags &= ~8 /* Synthesized */; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. - if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); - } return name; case 146 /* QualifiedName */: - return serializeQualifiedNameAsExpression(node, useFallback); + return serializeQualifiedNameAsExpression(node); } } /** @@ -63906,19 +64809,8 @@ var ts; * @param useFallback A value indicating whether to use logical operators to test for the * qualified name at runtime. */ - function serializeQualifiedNameAsExpression(node, useFallback) { - var left; - if (node.left.kind === 71 /* Identifier */) { - left = serializeEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); - } - else { - left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); - } - return ts.createPropertyAccess(left, node.right); + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); } /** * Gets an expression that points to the global "Symbol" constructor at runtime if it is @@ -64327,7 +65219,8 @@ var ts; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; @@ -64362,8 +65255,13 @@ var ts; /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } ts.setTextRange(enumStatement, node); - ts.setEmitFlags(enumStatement, emitFlags); + ts.addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); // Add a DeclarationMarker for the enum to preserve trailing comments and mark // the end of the declaration. @@ -64381,7 +65279,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -64510,7 +65408,7 @@ var ts; // })(m1 || (m1 = {})); // trailing comment module // ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(statement); return true; } @@ -64545,7 +65443,8 @@ var ts; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; @@ -64579,8 +65478,13 @@ var ts; /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } ts.setTextRange(moduleStatement, node); - ts.setEmitFlags(moduleStatement, emitFlags); + ts.addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); // Add a DeclarationMarker for the namespace to preserve trailing comments and mark // the end of the declaration. @@ -64622,7 +65526,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -65432,7 +66336,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -66039,7 +66943,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -66067,7 +66971,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependStatements(statements, leadingStatements); + ts.addStatementsAfterPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -67162,7 +68066,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -67417,7 +68321,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -67530,7 +68434,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -67640,7 +68544,7 @@ var ts; return 2 /* ReplaceWithReturn */; } // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis(), firstStatement); + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); // If we're actually replacing the original statement, we need to signal this to the caller. if (superCallExpression) { return 1 /* ReplaceSuperCapture */; @@ -67832,7 +68736,7 @@ var ts; captureThisForNode(statements, node, ts.createThis()); } } - function captureThisForNode(statements, node, initializer, originalStatement) { + function captureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -67840,7 +68744,6 @@ var ts; /*type*/ undefined, initializer) ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); - ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); } @@ -68170,7 +69073,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependStatements(statements, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { @@ -68432,7 +69335,7 @@ var ts; var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) - : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement), node, convertedLoopState && resetLabel); + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { @@ -68749,7 +69652,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependStatements(statements_4, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -70424,7 +71327,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -72662,7 +73565,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -72885,7 +73788,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -72948,9 +73851,9 @@ var ts; return visitFunctionDeclaration(node); case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 307 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 308 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -73176,7 +74079,7 @@ var ts; if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { // import "mod"; - return ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); } else { var variables = []; @@ -73197,18 +74100,20 @@ var ts; /*type*/ undefined, ts.getGeneratedNameForNode(node))); } } - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), - /*location*/ node)); + /*location*/ node), + /*original*/ node)); } } else if (namespaceDeclaration && ts.isDefaultImport(node)) { // import d, * as n from "mod"; statements = ts.append(statements, ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node)), - /*location*/ node) + /*location*/ node), + /*original*/ node) ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -73244,20 +74149,20 @@ var ts; var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); } else { - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), /*type*/ undefined, createRequireCall(node)) ], - /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node)); + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); } } else { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); } } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -73286,23 +74191,24 @@ var ts; var statements = []; // export { x, y } from "mod"; if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.setTextRange(ts.createVariableStatement( + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(generatedName, /*type*/ undefined, createRequireCall(node)) ])), - /*location*/ node)); + /*location*/ node), + /* original */ node)); } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); } return ts.singleOrMany(statements); } else { // export * from "mod"; - return ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); } } /** @@ -73408,7 +74314,7 @@ var ts; statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); } if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); } } else { @@ -74154,7 +75060,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -74882,9 +75788,9 @@ var ts; return visitCatchClause(node); case 216 /* Block */: return visitBlock(node); - case 307 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 308 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -75928,7 +76834,8 @@ var ts; 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | - 4 /* GenerateNamesForShadowedTypeParams */; + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; /** * Transforms a ts file into a .d.ts file * This process requires type information, which is retrieved through the emit resolver. Because of this, @@ -75948,6 +76855,7 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, @@ -75956,6 +76864,7 @@ var ts; reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode }; var errorNameNode; var currentSourceFile; @@ -76014,6 +76923,11 @@ var ts; } } } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } function trackSymbol(symbol, enclosingDeclaration, meaning) { if (symbol.flags & 262144 /* TypeParameter */) return; @@ -76041,7 +76955,7 @@ var ts; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; - var refs_1 = ts.createMap(); + refs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) @@ -76055,7 +76969,7 @@ var ts; getSymbolAccessibilityDiagnostic = throwDiagnostic; needsScopeFixMarker = false; resultHasScopeMarker = false; - collectReferences(sourceFile, refs_1); + collectReferences(sourceFile, refs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -76076,7 +76990,7 @@ var ts; bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); - refs_1.forEach(referenceVisitor_1); + refs.forEach(referenceVisitor_1); return bundle; } // Single source file @@ -76104,6 +77018,7 @@ var ts; combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; function getFileReferencesForUsedTypeReferences() { return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; @@ -76321,10 +77236,18 @@ var ts; if (!input) return undefined; // TODO: GH#18217 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); - if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { - var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); - if (newName) { - return ts.createLiteral(newName); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } } } return input; @@ -76853,6 +77776,15 @@ var ts; } return false; } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } function ensureModifiers(node, privateDeclaration) { var currentFlags = ts.getModifierFlags(node); var newFlags = ensureModifierFlags(node, privateDeclaration); @@ -76866,7 +77798,7 @@ var ts; var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; var parentIsFile = node.parent.kind === 277 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { - mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; } return maskModifierFlags(node, mask, additions); @@ -76885,7 +77817,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_8 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -76899,7 +77831,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_8(range); } } return prop; @@ -76925,6 +77857,11 @@ var ts; if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) } @@ -77061,7 +77998,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(309 /* Count */); + var enabledSyntaxKindFeatures = new Array(310 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -77408,7 +78345,7 @@ var ts; if (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { // The relative paths are relative to the common directory @@ -77614,7 +78551,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 304 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -77631,7 +78568,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 304 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -77810,7 +78747,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 304 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -77824,10 +78761,12 @@ var ts; var savedContainerPos = containerPos; var savedContainerEnd = containerEnd; var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments) { + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. containerPos = pos; } - if (!skipTrailingComments) { + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end @@ -78176,17 +79115,17 @@ var ts; if (sourceFile.kind === 278 /* Bundle */) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error var isJs = ts.isSourceFileJavaScript(sourceFile); - var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } @@ -78241,6 +79180,7 @@ var ts; }); var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; + var exportedModulesFromDeclarationEmit; // Emit each output file ts.performance.mark("beforePrint"); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); @@ -78250,6 +79190,7 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -78308,7 +79249,7 @@ var ts; // Setup and perform the transformation to retrieve declarations from the input files var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; - if (emitOnlyDtsFiles && !compilerOptions.declaration) { + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. // Do that here when emitting only dts files nonJsFiles.forEach(collectLinkedAliases); @@ -78337,6 +79278,10 @@ var ts; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } } declarationTransform.dispose(); } @@ -78975,9 +79920,9 @@ var ts; case 262 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return emitCommaList(node); } } @@ -81692,7 +82637,7 @@ var ts; case WatchLogLevel.TriggerOnly: return createFileWatcherWithTriggerLogging; case WatchLogLevel.Verbose: - return createFileWatcherWithLogging; + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; } } function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { @@ -81705,9 +82650,27 @@ var ts; } }; } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { return addWatch(host, file, function (fileName, cbOptional) { - var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); log(triggerredInfo); var start = ts.timestamp(); cb(fileName, cbOptional, passThrough); @@ -81837,7 +82800,7 @@ var ts; } } ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82199,6 +83162,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -82236,7 +83200,8 @@ var ts; var packageIdToSourceFile = ts.createMap(); // Maps from a SourceFile's `.path` to the name of the package it was imported with. var sourceFileToPackageName = ts.createMap(); - var redirectTargetsSet = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -82343,7 +83308,7 @@ var ts; getSourceFileFromReference: getSourceFileFromReference, getLibFileFromReference: getLibFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsMap: redirectTargetsMap, isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -82629,7 +83594,7 @@ var ts; fileChanged = false; newSourceFile = oldSourceFile; // Use the redirect. } - else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { // If a redirected-to source file changes, the redirect may be broken. if (newSourceFile !== oldSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -82758,7 +83723,7 @@ var ts; resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; - redirectTargetsSet = oldProgram.redirectTargetsSet; + redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -82950,10 +83915,7 @@ var ts; } function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { - // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a - // '/// ' directive. - if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { + if (ts.skipTypeChecking(sourceFile, options)) { return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); @@ -83347,7 +84309,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -83425,9 +84387,17 @@ var ts; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path - // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } } // If the file was previously found via a node_modules search, but is now being processed as a root file, // then everything it sucks in may also be marked incorrectly, and needs to be checked again. @@ -83480,7 +84450,7 @@ var ts; // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 - redirectTargetsSet.set(fileFromPackageId.path, true); + redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); @@ -83710,7 +84680,7 @@ var ts; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); allFilesBelongToPath = false; } } @@ -83727,6 +84697,7 @@ var ts; if (sourceFile === undefined) { return undefined; } + sourceFile.path = toPath(refPath); var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } @@ -83740,7 +84711,7 @@ var ts; ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 } function verifyCompilerOptions() { - if (options.strictPropertyInitialization && !options.strictNullChecks) { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { @@ -83800,14 +84771,14 @@ var ts; if (options.composite && rootNames.length < files.length) { var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_10 = function (file) { + var _loop_9 = function (file) { if (normalizedRootNames.every(function (r) { return r !== file; })) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); } }; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var file = sourceFiles_4[_i]; - _loop_10(file); + _loop_9(file); } } if (options.paths) { @@ -83864,7 +84835,7 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } - if (options.declarationMap && !options.declaration) { + if (options.declarationMap && !ts.getEmitDeclarations(options)) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); } if (options.lib && options.noLib) { @@ -83905,6 +84876,10 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } + // Any emit other than common js is error + else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + } } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted @@ -84036,12 +85011,12 @@ var ts; } function createDiagnosticForReference(index, message, arg0, arg1) { var referencesSyntax = getProjectReferencesSyntax(); - if (referencesSyntax) { - if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { - return; - } + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); @@ -84091,14 +85066,6 @@ var ts; } return !!props.length; } - function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { - if (arrayLiteral.elements.length <= index) { - // Out-of-bounds - return false; - } - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); - return false; // TODO: GH#18217 This function always returns `false`!` - } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -84151,7 +85118,8 @@ var ts; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; /** - * Returns the target config filename of a project reference + * Returns the target config filename of a project reference. + * Note: The file might not exist. */ function resolveProjectReferencePath(host, ref) { if (!host.fileExists(ref.path)) { @@ -84171,7 +85139,6 @@ var ts; switch (extension) { case ".ts" /* Ts */: case ".d.ts" /* Dts */: - case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check // These are always allowed. return undefined; case ".tsx" /* Tsx */: @@ -84180,6 +85147,8 @@ var ts; return needJsx() || needAllowJs(); case ".js" /* Js */: return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); } function needJsx() { return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; @@ -84187,6 +85156,9 @@ var ts; function needAllowJs() { return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } } ts.getResolutionDiagnostic = getResolutionDiagnostic; function getModuleNames(_a) { @@ -84208,7 +85180,7 @@ var ts; function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -84219,6 +85191,22 @@ var ts; (function (ts) { var BuilderState; (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.path; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -84231,12 +85219,9 @@ var ts; var checker = program.getTypeChecker(); for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); } } } @@ -84281,6 +85266,7 @@ var ts; function create(newProgram, getCanonicalFileName, oldState) { var fileInfos = ts.createMap(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; var hasCalledUpdateShapeSignature = ts.createMap(); var useOldState = canReuseOldState(referencedMap, oldState); // Create the reference map, and set the file infos @@ -84293,12 +85279,20 @@ var ts; if (newReferences) { referencedMap.set(sourceFile.path, newReferences); } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } } fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); } return { fileInfos: fileInfos, referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, allFilesExcludingDefaultLibraryFile: undefined, allFileNames: undefined @@ -84308,7 +85302,7 @@ var ts; /** * Gets the files affected by the path from the program */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { // Since the operation could be cancelled, the signatures are always stored in the cache // They will be commited once it is safe to use them // eg when calling this api from tsserver, if there is no cancellation of the operation @@ -84318,10 +85312,10 @@ var ts; if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); if (!cacheToUpdateSignature) { // Commit all the signatures in the signature cache updateSignaturesFromCache(state, signatureCache); @@ -84343,8 +85337,9 @@ var ts; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { return false; @@ -84361,6 +85356,9 @@ var ts; var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } } else { latestSignature = prevSignature; // TODO: GH#18217 @@ -84369,6 +85367,44 @@ var ts; cacheToUpdateSignature.set(sourceFile.path, latestSignature); return !prevSignature || latestSignature !== prevSignature; } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -84478,7 +85514,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -84498,7 +85534,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 queue, getReferencedByPaths(state, currentPath)); } @@ -84529,7 +85565,8 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -84565,6 +85602,10 @@ var ts; var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); } } }); @@ -84586,14 +85627,14 @@ var ts; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { - var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var seenAffectedFiles = state.seenAffectedFiles; var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 while (affectedFilesIndex < affectedFiles.length) { var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.path)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - semanticDiagnosticsPerFile.delete(affectedFile.path); + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); return affectedFile; } seenAffectedFiles.set(affectedFile.path, true); @@ -84605,6 +85646,7 @@ var ts; // Commit the changes in file signature ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); state.affectedFiles = undefined; } // Get next changed file @@ -84622,13 +85664,66 @@ var ts; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; - state.semanticDiagnosticsPerFile.delete(nextKey.value); state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return false; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } /** * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly @@ -84895,6 +85990,7 @@ var ts; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -84952,6 +86048,7 @@ var ts; function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); @@ -84991,17 +86088,19 @@ var ts; perDirectoryResolvedModuleNames.clear(); nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); - clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); @@ -85053,7 +86152,7 @@ var ts; perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); - watchFailedLookupLocationOfResolution(resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } @@ -85149,14 +86248,23 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - // Always watch root directory recursively - return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, "/node_modules/")) { + while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } @@ -85185,16 +86293,25 @@ var ts; function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); } - function watchFailedLookupLocationOfResolution(resolution) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { // No need to set the resolution refCount - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { - return; - } - if (resolution.refCount !== undefined) { - resolution.refCount++; - return; + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } } - resolution.refCount = 1; + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); var failedLookupLocations = resolution.failedLookupLocations; var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { @@ -85209,6 +86326,7 @@ var ts; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); } if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); setAtRoot = true; } else { @@ -85217,10 +86335,19 @@ var ts; } } if (setAtRoot) { - // This is always recursive - setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { @@ -85232,7 +86359,7 @@ var ts; } } function stopWatchFailedLookupLocationOfResolution(resolution) { - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + if (!resolution.refCount) { return; } resolution.refCount--; @@ -85455,23 +86582,36 @@ var ts; } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); -// Used by importFixes to synthesize import module specifiers. +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { // Note: importingSourceFile is just for usesJsExtensionOnImports - function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences) { + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, toFileName, info.getCanonicalFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { + var isBundle = (compilerOptions.out || compilerOptions.outFile); + if (isBundle && host.getCommonSourceDirectory) { + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); + } + var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; + return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + } + moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) return [[ambient]]; @@ -85479,7 +86619,8 @@ var ts; if (!files) { return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); } - var modulePaths = getAllModulePaths(files, ts.getSourceFileOfNode(moduleSymbol.valueDeclaration).fileName, info.getCanonicalFileName, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); @@ -85564,64 +86705,66 @@ var ts; return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; }) || false; } - function discoverProbableSymlinks(files, getCanonicalFileName, host) { + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); var symlinks = ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; }); }); - var result = ts.createMap(); - if (symlinks) { - var currentDirectory = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { - var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; - var resolvedParts = ts.getPathComponents(ts.toPath(resolvedPath, currentDirectory, getCanonicalFileName)); - var originalParts = ts.getPathComponents(ts.toPath(originalPath, currentDirectory, getCanonicalFileName)); - while (compareStrings(resolvedParts[resolvedParts.length - 1], originalParts[originalParts.length - 1]) === 0 /* EqualTo */) { - resolvedParts.pop(); - originalParts.pop(); - } - result.set(ts.getPathFromPathComponents(originalParts), ts.getPathFromPathComponents(resolvedParts)); - } + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); } return result; } - function getAllModulePathsUsingIndirectSymlinks(files, target, getCanonicalFileName, host) { - var links = discoverProbableSymlinks(files, getCanonicalFileName, host); - var paths = ts.arrayFrom(links.keys()); - var options; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, paths_2 = paths; _i < paths_2.length; _i++) { - var path = paths_2[_i]; - var resolved = links.get(path); - if (compareStrings(target.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */) { - var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - if (!options) - options = []; - options.push(option); - } - } - } - if (options) { - options.push(target); // Since these are speculative, we also include the original resolved name as a possibility - return options; - } - return [target]; - } /** * Looks for existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(files, importedFileName, getCanonicalFileName, host) { - var symlinks = ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === importedFileName ? res.originalPath : undefined; - }); + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } }); - return symlinks.length === 0 ? getAllModulePathsUsingIndirectSymlinks(files, ts.getNormalizedAbsolutePath(importedFileName, host.getCurrentDirectory ? host.getCurrentDirectory() : ""), getCanonicalFileName, host) : symlinks; + result.push.apply(result, targets); + return result; } function getRelativePathNParents(relativePath) { var components = ts.getPathComponents(relativePath); @@ -85634,8 +86777,8 @@ var ts; return components.length - 1; } function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { return decl.name.text; } } @@ -85645,10 +86788,7 @@ var ts; var patternText_1 = _a[_i]; var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { + if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && @@ -85761,7 +86901,7 @@ var ts; partEnd = fullPath.indexOf("/", partStart + 1); switch (state) { case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { topLevelNodeModulesIndex = partStart; topLevelPackageNameIndex = partEnd; state = 1 /* NodeModules */; @@ -85778,7 +86918,7 @@ var ts; } break; case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { state = 1 /* NodeModules */; } else { @@ -85963,6 +87103,7 @@ var ts; createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; } var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); @@ -86091,16 +87232,15 @@ var ts; }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); - if (configFileName) { + if (configFileName && !host.configFileParsingResult) { newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); - if (host.configFileParsingResult) { - setConfigFileParsingResult(host.configFileParsingResult); - } - else { - ts.Debug.assert(!rootFileNames); - parseConfigFile(); - } + ts.Debug.assert(!rootFileNames); + parseConfigFile(); newLine = updateNewLine(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); @@ -86648,7 +87788,7 @@ var ts; } var outputs = []; outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); - if (configFile.options.declaration && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); if (configFile.options.declarationMap) { @@ -86663,7 +87803,7 @@ var ts; } var outputs = []; outputs.push(project.options.outFile); - if (project.options.declaration) { + if (ts.getEmitDeclarations(project.options)) { var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { @@ -86815,6 +87955,7 @@ var ts; return builder.cleanAllProjects(); } if (watch) { + builder.buildAllProjects(); builder.startWatching(); return undefined; } @@ -86871,7 +88012,7 @@ var ts; // Everything is broken - we don't even know what to watch. Give up. return; } - var _loop_11 = function (resolved) { + var _loop_10 = function (resolved) { var cfg = configFileCache.parseConfigFile(resolved); if (cfg) { // Watch this file @@ -86898,7 +88039,7 @@ var ts; }; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var resolved = _a[_i]; - _loop_11(resolved); + _loop_10(resolved); } function invalidateProjectAndScheduleBuilds(resolved) { invalidateProject(resolved); @@ -87068,7 +88209,7 @@ var ts; }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { resultFlags |= BuildResultFlags.SyntaxErrors; for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { @@ -87079,7 +88220,7 @@ var ts; return resultFlags; } // Don't emit .d.ts if there are decl file errors - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { resultFlags |= BuildResultFlags.DeclarationEmitErrors; @@ -87133,15 +88274,16 @@ var ts; if (context.options.dry) { return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) + if (context.options.verbose) { buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { var file = outputs_1[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file)); + priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); } compilerHost.setModifiedTime(file, now); } @@ -87339,7 +88481,7 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile); + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; if (inputTime > newestInputFileTime) { newestInputFileName = inputFile; newestInputFileTime = inputTime; @@ -87368,7 +88510,7 @@ var ts; missingOutputFileName = output; break; } - var outputTime = host.getModifiedTime(output); + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; if (outputTime < oldestOutputFileTime) { oldestOutputFileTime = outputTime; oldestOutputFileName = output; @@ -87393,7 +88535,8 @@ var ts; newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } else { - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, host.getModifiedTime(output)); + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } @@ -87512,7 +88655,7 @@ var ts; // Don't report status on "solution" projects break; default: - ts.assertTypeIsNever(status); + ts.assertType(status); } } ts.formatUpToDateStatus = formatUpToDateStatus; @@ -87830,7 +88973,7 @@ var ts; case 240 /* TypeAliasDeclaration */: case 166 /* TypeLiteral */: return 2 /* Type */; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; case 276 /* EnumMember */: @@ -87958,16 +89101,20 @@ var ts; return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 189 /* CallExpression */); + return isCallOrNewExpressionTargetWorker(node, ts.isCallExpression); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 190 /* NewExpression */); + return isCallOrNewExpressionTargetWorker(node, ts.isNewExpression); } ts.isNewExpressionTarget = isNewExpressionTarget; - function isCallOrNewExpressionTarget(node, kind) { + function isCallOrNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallOrNewExpression); + } + ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget; + function isCallOrNewExpressionTargetWorker(node, pred) { var target = climbPastPropertyAccess(node); - return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && pred(target.parent) && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -88081,7 +89228,7 @@ var ts; case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; case 240 /* TypeAliasDeclaration */: case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return "type" /* typeElement */; case 241 /* EnumDeclaration */: return "enum" /* enumElement */; case 235 /* VariableDeclaration */: @@ -88132,7 +89279,7 @@ var ts; case 6 /* Prototype */: return "local class" /* localClassElement */; default: { - ts.assertTypeIsNever(kind); + ts.assertType(kind); return "" /* unknown */; } } @@ -88410,7 +89557,7 @@ var ts; var current = sourceFile; outer: while (true) { // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { var child = _a[_i]; var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { @@ -88621,7 +89768,21 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(tokenIn, sourceFile) { + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { var token = tokenIn; // This function determines if the node could be type argument position // Since during editing, when type argument list is not complete, @@ -88701,7 +89862,7 @@ var ts; } return undefined; } - ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; /** * Returns true if the cursor at position in sourceFile is within a comment. * @@ -88833,6 +89994,10 @@ var ts; return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { return ts.createTextSpanFromBounds(range.pos, range.end); } @@ -88852,6 +90017,7 @@ var ts; ts.typeKeywords = [ 119 /* AnyKeyword */, 122 /* BooleanKeyword */, + 86 /* FalseKeyword */, 128 /* KeyOfKeyword */, 131 /* NeverKeyword */, 95 /* NullKeyword */, @@ -88859,6 +90025,7 @@ var ts; 135 /* ObjectKeyword */, 137 /* StringKeyword */, 138 /* SymbolKeyword */, + 101 /* TrueKeyword */, 105 /* VoidKeyword */, 140 /* UndefinedKeyword */, 141 /* UniqueKeyword */, @@ -88870,8 +90037,7 @@ var ts; ts.isTypeKeyword = isTypeKeyword; /** True if the symbol is for an external module, as opposed to a namespace. */ function isExternalModuleSymbol(moduleSymbol) { - ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); - return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; function nodeSeenTracker() { @@ -88895,13 +90061,13 @@ var ts; } ts.repeatString = repeatString; function skipConstraint(type) { - return type.isTypeParameter() ? type.getConstraint() : type; // TODO: GH#18217 + return type.isTypeParameter() ? type.getConstraint() || type : type; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { return name.kind === 147 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal - ? ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined + ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.getTextOfIdentifierOrLiteral(name); } ts.getNameFromPropertyName = getNameFromPropertyName; @@ -88956,6 +90122,14 @@ var ts; } } ts.getQuotePreference = getQuotePreference; + function getQuoteFromPreference(qp) { + switch (qp) { + case 0 /* Single */: return "'"; + case 1 /* Double */: return '"'; + default: return ts.Debug.assertNever(qp); + } + } + ts.getQuoteFromPreference = getQuoteFromPreference; function symbolNameNoDefault(symbol) { var escaped = symbolEscapedNameNoDefault(symbol); return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); @@ -89013,56 +90187,6 @@ var ts; return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; } ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; - var NodeSet = /** @class */ (function () { - function NodeSet() { - this.map = ts.createMap(); - } - NodeSet.prototype.add = function (node) { - this.map.set(String(ts.getNodeId(node)), node); - }; - NodeSet.prototype.has = function (node) { - return this.map.has(String(ts.getNodeId(node))); - }; - NodeSet.prototype.forEach = function (cb) { - this.map.forEach(cb); - }; - NodeSet.prototype.some = function (pred) { - return ts.forEachEntry(this.map, pred) || false; - }; - return NodeSet; - }()); - ts.NodeSet = NodeSet; - var NodeMap = /** @class */ (function () { - function NodeMap() { - this.map = ts.createMap(); - } - NodeMap.prototype.get = function (node) { - var res = this.map.get(String(ts.getNodeId(node))); - return res && res.value; - }; - NodeMap.prototype.getOrUpdate = function (node, setValue) { - var res = this.get(node); - if (res) - return res; - var value = setValue(); - this.set(node, value); - return value; - }; - NodeMap.prototype.set = function (node, value) { - this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); - }; - NodeMap.prototype.has = function (node) { - return this.map.has(String(ts.getNodeId(node))); - }; - NodeMap.prototype.forEach = function (cb) { - this.map.forEach(function (_a) { - var node = _a.node, value = _a.value; - return cb(value, node); - }); - }; - return NodeMap; - }()); - ts.NodeMap = NodeMap; function getParentNodeInSpan(node, file, span) { if (!node) return undefined; @@ -89093,6 +90217,14 @@ var ts; } } ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -89103,13 +90235,24 @@ var ts; ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios var displayParts; var lineStart; var indent; + var length; resetWriter(); var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { - displayParts: function () { return displayParts; }, + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, @@ -89138,23 +90281,35 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { + if (length > absoluteMaximumLength) + return; if (lineStart) { var indentString = ts.getIndentString(indent); if (indentString) { + length += indentString.length; displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); } lineStart = false; } } function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(displayPart(text, kind)); } function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(symbolPart(text, symbol)); } function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; displayParts.push(lineBreakPart()); lineStart = true; } @@ -89162,6 +90317,7 @@ var ts; displayParts = []; lineStart = true; indent = 0; + length = 0; } } function symbolPart(text, symbol) { @@ -89355,8 +90511,30 @@ var ts; return clone; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; - function getSynthesizedDeepCloneWorker(node) { - var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone; + if (node && ts.isIdentifier(node) && renameMap && checker) { + var symbol = checker.getSymbolAtLocation(node); + var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); + if (renameInfo) { + clone = ts.createIdentifier(renameInfo.text); + } + } + if (!clone) { + clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + } + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + if (callback && node) + callback(node, clone); + return clone; + } + ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames; + function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) { + var visited = (renameMap || checker || callback) ? + ts.visitEachChild(node, wrapper, ts.nullTransformationContext) : + ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. var clone_1 = ts.getSynthesizedClone(node); @@ -89373,6 +90551,9 @@ var ts; // would have made. visited.parent = undefined; return visited; + function wrapper(node) { + return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback); + } } function getSynthesizedDeepClones(nodes, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = true; } @@ -90127,18 +91308,18 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 297 /* JSDocReturnTag */: + case 298 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -90800,6 +91981,19 @@ var ts; (function (ts) { var Completions; (function (Completions) { + var SymbolOriginInfoKind; + (function (SymbolOriginInfoKind) { + SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 0] = "ThisType"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 1] = "SymbolMemberNoExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 2] = "SymbolMemberExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 3] = "Export"; + })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); + function originIsSymbolMember(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 1 /* SymbolMemberNoExport */; + } + function originIsExport(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 3 /* Export */; + } var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; @@ -90823,8 +92017,8 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) - return undefined; // TODO: GH#18217 + if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined @@ -90888,20 +92082,22 @@ var ts; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; - if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { + if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
- // The completion list at "1" will contain "div" with type any + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, - entries: [{ - name: tagName.getFullText(), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: "0", - }] }; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { @@ -90970,12 +92166,12 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (origin && origin.type === "this-type") { + if (origin && origin.kind === 0 /* ThisType */) { insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. - else if ((origin && origin.type === "symbol-member" || needsConvertPropertyAccess) && propertyAccessToConvert) { + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. @@ -91006,7 +92202,7 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(!!origin && origin.type === "export"), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), insertText: insertText, replacementSpan: replacementSpan, @@ -91032,7 +92228,7 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); @@ -91113,6 +92309,8 @@ var ts; return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 171 /* UnionType */: + return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; default: return undefined; } @@ -91229,7 +92427,7 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -91264,7 +92462,7 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -91307,14 +92505,14 @@ var ts; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; } - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, allSourceFiles, preferences) { + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo || symbolOriginInfo.type !== "export") { + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { return { codeActions: undefined, sourceDisplay: undefined }; } var moduleSymbol = symbolOriginInfo.moduleSymbol; var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, allSourceFiles, formatContext, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { @@ -91463,7 +92661,7 @@ var ts; currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 302 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 303 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -91520,6 +92718,9 @@ var ts; case 146 /* QualifiedName */: node = parent.left; break; + case 242 /* ModuleDeclaration */: + node = parent.name; + break; case 181 /* ImportType */: case 212 /* MetaProperty */: node = parent; @@ -91626,11 +92827,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: - case 297 /* JSDocReturnTag */: - case 299 /* JSDocTypeTag */: - case 301 /* JSDocTypedefTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: + case 298 /* JSDocReturnTag */: + case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypedefTag */: return true; default: return false; @@ -91643,8 +92844,11 @@ var ts; var isImportType = ts.isLiteralImportTypeNode(node); var isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !node.isTypeOf) || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); - var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile)); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)); if (ts.isEntityName(node) || isImportType) { + var isNamespaceName = ts.isModuleDeclaration(node.parent); + if (isNamespaceName) + isNewIdentifierLocation = true; var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { symbol = ts.skipAlias(symbol, typeChecker); @@ -91653,14 +92857,17 @@ var ts; var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; - var isValidAccess = allowTypeOrValue ? - // Any kind is allowed when dotting off namespace in internal import equals declaration - function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : - isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + var isValidAccess = isNamespaceName + // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. + ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + : allowTypeOrValue ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { - var symbol_1 = exportedSymbols_1[_i]; - if (isValidAccess(symbol_1)) { - symbols.push(symbol_1); + var exportedSymbol = exportedSymbols_1[_i]; + if (isValidAccess(exportedSymbol)) { + symbols.push(exportedSymbol); } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). @@ -91711,7 +92918,9 @@ var ts; var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { symbols.push(firstAccessibleSymbol); - symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = { type: "symbol-member" }; + var moduleSymbol = firstAccessibleSymbol.parent; + symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = + !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) ? { kind: 1 /* SymbolMemberNoExport */ } : { kind: 2 /* SymbolMemberExport */, moduleSymbol: moduleSymbol, isDefaultExport: false }; } } else { @@ -91801,7 +93010,7 @@ var ts; if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 0 /* ThisType */ }; symbols.push(symbol); } } @@ -91843,7 +93052,7 @@ var ts; } function filterGlobalCompletion(symbols) { var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile); + var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) keywordFilters = 5 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { @@ -91936,7 +93145,7 @@ var ts; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + var origin = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; @@ -92002,7 +93211,8 @@ var ts; function isNewIdentifierDefinitionLocation(previousToken) { if (previousToken) { var containingNodeKind = previousToken.parent.kind; - switch (previousToken.kind) { + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(previousToken)) { case 26 /* CommaToken */: return containingNodeKind === 189 /* CallExpression */ // func( a, | || containingNodeKind === 155 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ @@ -92039,13 +93249,6 @@ var ts; case 113 /* ProtectedKeyword */: return containingNodeKind === 152 /* PropertyDeclaration */; // class A{ public | } - // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: - return true; - } } return false; } @@ -92588,7 +93791,7 @@ var ts; case 3 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); case 4 /* FunctionLikeBodyKeywords */: - return !isClassMemberCompletionKeyword(kind); + return isFunctionLikeBodyKeyword(kind); case 5 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: @@ -92611,6 +93814,9 @@ var ts; return ts.isClassMemberModifier(kind); } } + function isFunctionLikeBodyKeyword(kind) { + return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } @@ -92657,7 +93863,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 303 /* SyntaxList */: + case 304 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -92765,7 +93971,7 @@ var ts; return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; if (!sourceFilesSet.has(fileName)) { - ts.Debug.assert(program.redirectTargetsSet.has(fileName)); + ts.Debug.assert(program.redirectTargetsMap.has(fileName)); var redirectTarget_1 = program.getSourceFile(fileName); var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; @@ -94077,7 +95283,8 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -94482,7 +95689,7 @@ var ts; - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. */ var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); - if (exposedByParent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } var scope; @@ -95115,7 +96322,8 @@ var ts; // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - var res_1 = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), fromRoot); + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); if (res_1) return res_1; // If the location is name of property symbol from object literal destructuring pattern @@ -95180,14 +96388,6 @@ var ts; return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); }); } - /** Gets all symbols for one property. Does not get symbols for every property. */ - function getPropertySymbolsFromContextualType(node, checker) { - var contextualType = checker.getContextualType(node.parent); - var name = ts.getNameFromPropertyName(node.name); - var symbol = contextualType && name && contextualType.getProperty(name); - return symbol ? [symbol] : - contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; // TODO: GH#18217 - } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class @@ -95271,11 +96471,11 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName); - var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); @@ -95283,16 +96483,28 @@ var ts; } ts.getEditsForFileRename = getEditsForFileRename; // exported for tests - function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName) { + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return function (path) { - if (getCanonicalFileName(path) === canonicalOldPath) + var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) return newFileOrDirPath; - var suffix = ts.tryRemoveDirectoryPrefix(path, canonicalOldPath, getCanonicalFileName); + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; - }; + } } ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); + } function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; if (!configFile) @@ -95386,11 +96598,11 @@ var ts; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. // TODO:GH#18217 - ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, program) + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences) + ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) : undefined; }); }; @@ -95416,14 +96628,14 @@ var ts; var resolved = host.resolveModuleNames ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); - return getSourceFileToImportFromResolved(resolved, oldToNew, program); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); } } - function getSourceFileToImportFromResolved(resolved, oldToNew, program) { - return resolved && ((resolved.resolvedModule && getIfInProgram(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfInProgram)); - function getIfInProgram(oldLocation) { + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); + function getIfExists(oldLocation) { var newLocation = oldToNew(oldLocation); - return program.getSourceFile(oldLocation) || newLocation !== undefined && program.getSourceFile(newLocation) + return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } : undefined; } @@ -95490,12 +96702,12 @@ var ts; // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || - // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias - symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { return [sigInfo]; } else { - var defs = getDefinitionFromSymbol(typeChecker, symbol, node); + var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; // For a 'super()' call, put the signature first, else put the variable first. return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } @@ -95522,13 +96734,12 @@ var ts; // bar(({pr/*goto*/op1})=>{}); if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && (node === (parent.propertyName || parent.name))) { + var name_3 = ts.getNameFromPropertyName(node); var type = typeChecker.getTypeAtLocation(parent.parent); - if (type) { - var propSymbols = ts.getPropertySymbolsFromType(type, node); - if (propSymbols) { - return ts.flatMap(propSymbols, function (propSymbol) { return getDefinitionFromSymbol(typeChecker, propSymbol, node); }); - } - } + return name_3 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_3); + return prop && getDefinitionFromSymbol(typeChecker, prop, node); + }); } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. @@ -95540,10 +96751,13 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element && typeChecker.getContextualType(element.parent)) { - return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { - return getDefinitionFromSymbol(typeChecker, propertySymbol, node); - }); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -95583,16 +96797,32 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); - if (!type) { + if (!symbol) return undefined; - } - if (type.isUnion() && !(type.flags & 32 /* Enum */)) { - return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); - } - return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); + var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); + var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); + // If a function returns 'void' or some other type with no definition, just return the function definition. + return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function definitionFromType(type, checker, node) { + return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) { + return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node); + }); + } + function tryGetReturnTypeOfFunction(symbol, type, checker) { + // If the type is just a function's inferred type, + // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway. + if (type.symbol === symbol || + // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { + var sigs = type.getCallSignatures(); + if (sigs.length === 1) + return checker.getReturnTypeOfSignature(ts.first(sigs)); + } + return undefined; + } function getDefinitionAndBoundSpan(program, sourceFile, position) { var definitions = getDefinitionAtPosition(program, sourceFile, position); if (!definitions || definitions.length === 0) { @@ -95667,7 +96897,7 @@ var ts; } } function getCallSignatureDefinition() { - return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) : undefined; } @@ -95741,48 +96971,83 @@ var ts; var JsDoc; (function (JsDoc) { var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", "augments", "author", - "argument", "borrows", "callback", "class", + "classdesc", "constant", "constructor", "constructs", + "copyright", "default", "deprecated", "description", + "emits", + "enum", "event", "example", + "exports", "extends", + "external", "field", - "fileOverview", + "file", + "fileoverview", + "fires", "function", + "generator", + "global", + "hideconstructor", + "host", "ignore", - "inheritDoc", + "implements", + "inheritdoc", "inner", + "instance", + "interface", + "kind", "lends", - "link", - "memberOf", + "license", + "listens", + "member", + "memberof", "method", + "mixes", + "module", "name", "namespace", + "override", + "package", "param", "private", - "prop", "property", + "protected", "public", + "readonly", "requires", "returns", "see", "since", "static", + "summary", "template", + "this", "throws", + "todo", + "tutorial", "type", "typedef", - "version" + "var", + "variation", + "version", + "virtual", + "yields" ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; @@ -95810,11 +97075,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: return [declaration]; case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -95837,14 +97102,14 @@ var ts; switch (tag.kind) { case 293 /* JSDocAugmentsTag */: return withNode(tag.class); - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: - case 302 /* JSDocPropertyTag */: - case 296 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -95970,13 +97235,15 @@ var ts; * be performed. */ function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { - // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); + if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { + // Non-empty comment already exists. return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var tokenStart = tokenAtPos.getStart(sourceFile); - if (!tokenAtPos || tokenStart < position) { + // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.) + if (!existingDocComment && tokenStart < position) { return undefined; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); @@ -96025,45 +97292,48 @@ var ts; }).join(""); } function getCommentOwnerInfo(tokenAtPos) { - for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 153 /* MethodSignature */: - var parameters = commentOwner.parameters; - return { commentOwner: commentOwner, parameters: parameters }; - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 151 /* PropertySignature */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 240 /* TypeAliasDeclaration */: - return { commentOwner: commentOwner }; - case 217 /* 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 277 /* SourceFile */: - return undefined; - case 242 /* 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 === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 202 /* 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.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + } + function getCommentOwnerInfoWorker(commentOwner) { + switch (commentOwner.kind) { + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 153 /* MethodSignature */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 273 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer); + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 151 /* PropertySignature */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 240 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; + case 217 /* 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 277 /* SourceFile */: + return "quit"; + case 242 /* 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 === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 202 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + return "quit"; } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; } } } @@ -96104,7 +97374,7 @@ var ts; var rawItems = []; var _loop_4 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { + if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; } sourceFile.getNamedDeclarations().forEach(function (declarations, name) { @@ -96157,45 +97427,28 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - if (name && ts.isPropertyNameLiteral(name)) { - containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); - return true; - } - else if (name && name.kind === 147 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; - } + return !!name && (pushLiteral(name, containers) || name.kind === 147 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // // [X.Y.Z]() { } - function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - if (ts.isPropertyNameLiteral(expression)) { - var text = ts.getTextOfIdentifierOrLiteral(expression); - if (includeLastPortion) { - containers.unshift(text); - } - return true; - } - if (ts.isPropertyAccessExpression(expression)) { - if (includeLastPortion) { - containers.unshift(expression.name.text); - } - return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true); - } - return false; + function tryAddComputedPropertyName(expression, containers) { + return pushLiteral(expression, containers) + || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers); + } + function pushLiteral(node, containers) { + return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true); } 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 && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { + if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } + // Don't include the last portion. + containers.shift(); // Now, walk up our containers, adding all their names to the container array. var container = ts.getContainerNode(declaration); while (container) { @@ -96204,7 +97457,7 @@ var ts; } container = ts.getContainerNode(container); } - return containers; + return containers.reverse(); } function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. @@ -96343,7 +97596,7 @@ var ts; /** Call after calling `startNode` and adding children to it. */ function endNode() { if (parent.children) { - mergeChildren(parent.children); + mergeChildren(parent.children, parent); sortChildren(parent.children); } parent = parentsStack.pop(); @@ -96499,7 +97752,7 @@ var ts; } } /** Merge declarations of the same kind. */ - function mergeChildren(children) { + function mergeChildren(children, node) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var declName = ts.getNameOfDeclaration(child.node); @@ -96516,7 +97769,7 @@ var ts; if (itemsWithSameName instanceof Array) { for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { var itemWithSameName = itemsWithSameName_1[_i]; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } } @@ -96525,7 +97778,7 @@ var ts; } else { var itemWithSameName = itemsWithSameName; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } nameToItems.set(name, [itemWithSameName, child]); @@ -96533,16 +97786,16 @@ var ts; } }); } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { merge(a, b); return true; } return false; } /** a and b have the same name, but they may not be mergeable. */ - function shouldReallyMerge(a, b) { - if (a.kind !== b.kind) { + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { return false; } switch (a.kind) { @@ -96557,6 +97810,12 @@ var ts; return true; } } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { @@ -96573,7 +97832,7 @@ var ts; } target.children = ts.concatenate(target.children, source.children); if (target.children) { - mergeChildren(target.children); + mergeChildren(target.children, target); sortChildren(target.children); } } @@ -96595,7 +97854,7 @@ var ts; return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); - if (declName) { + if (declName && ts.isPropertyName(declName)) { return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { @@ -96672,7 +97931,7 @@ var ts; case 242 /* ModuleDeclaration */: case 277 /* SourceFile */: case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return true; case 155 /* Constructor */: @@ -96773,7 +98032,7 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 242 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217 + return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { return !member.name || member.name.kind === 147 /* ComputedPropertyName */; @@ -97295,6 +98554,23 @@ var ts; return spanForObjectOrArrayLiteral(n); case 185 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); + case 258 /* JsxElement */: + return spanForJSXElement(n); + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 17 /* OpenBraceToken */; } @@ -98153,7 +99429,7 @@ var ts; if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 147 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); @@ -98212,17 +99488,11 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - var ArgumentListKind; - (function (ArgumentListKind) { - ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; - ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; - ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; - ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind || (ArgumentListKind = {})); var InvocationKind; (function (InvocationKind) { InvocationKind[InvocationKind["Call"] = 0] = "Call"; InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual"; })(InvocationKind || (InvocationKind = {})); function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { var typeChecker = program.getTypeChecker(); @@ -98232,93 +99502,124 @@ var ts; // We are at the beginning of the file return undefined; } - if (shouldCarefullyCheckContext(triggerReason)) { - // In the middle of a string, don't provide signature help unless the user explicitly requested it. - if (ts.isInString(sourceFile, position, startingToken)) { - return undefined; - } + // Only need to be careful if the user typed a character and signature help wasn't showing. + var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { + return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); - // Semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - if (ts.isSourceFileJavaScript(sourceFile)) { - return createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken); - } - return undefined; + return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function shouldCarefullyCheckContext(reason) { - // Only need to be careful if the user typed a character and signature help wasn't showing. - return !!reason && reason.kind === "characterTyped"; - } - function getCandidateInfo(argumentInfo, checker) { - var invocation = argumentInfo.invocation; - if (invocation.kind === 0 /* Call */) { - var candidates = []; - var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = _a.invocation, argumentCount = _a.argumentCount; + switch (invocation.kind) { + case 0 /* Call */: { + if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { + return undefined; + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + } + case 1 /* TypeArgs */: { + if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + case 2 /* Contextual */: + return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + default: + return ts.Debug.assertNever(invocation); } - else { - var type = checker.getTypeAtLocation(invocation.called); // TODO: GH#18217 - var signatures = ts.isNewExpression(invocation.called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); - var candidates = signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= argumentInfo.argumentCount; }); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + function isSyntacticOwner(startingToken, node, sourceFile) { + if (!ts.isCallOrNewExpression(node)) + return false; + var invocationChildren = node.getChildren(sourceFile); + switch (startingToken.kind) { + case 19 /* OpenParenToken */: + return ts.contains(invocationChildren, startingToken); + case 26 /* CommaToken */: { + var containingList = ts.findContainingList(startingToken); + return !!containingList && ts.contains(invocationChildren, containingList); + } + case 27 /* LessThanToken */: + return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + default: + return false; } } function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + if (argumentInfo.invocation.kind === 2 /* Contextual */) + return undefined; // See if we can find some symbol with the call expression name that has call signatures. var expression = getExpressionFromInvocation(argumentInfo.invocation); - var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; - if (!name || !name.escapedText) { - return undefined; - } + var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined; var typeChecker = program.getTypeChecker(); - var _loop_6 = function (sourceFile) { - var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = nameToDeclarations.get(name.text); - if (declarations) { - var _loop_7 = function (declaration) { - var symbol = declaration.symbol; - if (symbol) { - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); - if (type) { - var callSignatures_1 = type.getCallSignatures(); - if (callSignatures_1 && callSignatures_1.length) { - return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; - } - } - } - }; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; - var state_3 = _loop_7(declaration); - if (typeof state_3 === "object") - return state_3; + return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) { + return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) { + var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration); + var callSignatures = type && type.getCallSignatures(); + if (callSignatures && callSignatures.length) { + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); }); } - } - }; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - var state_2 = _loop_6(sourceFile); - if (typeof state_2 === "object") - return state_2.value; - } + }); + }); + } + function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(calledExpression, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); - return !info || info.kind === 0 /* TypeArguments */ || info.invocation.kind === 1 /* TypeArgs */ ? undefined + return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; } SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; + function getArgumentOrParameterListInfo(node, sourceFile) { + var info = getArgumentOrParameterListAndIndex(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex; + var argumentCount = getArgumentCount(list); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + } + function getArgumentOrParameterListAndIndex(node, sourceFile) { + if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. + return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; + } + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + var list = ts.findContainingList(node); + return list && { list: list, argumentIndex: getArgumentIndex(list, node) }; + } + } /** * Returns relevant information for the argument list and the current argument if we are * in the argument of an invocation; returns undefined otherwise. @@ -98327,8 +99628,6 @@ var ts; var parent = node.parent; if (ts.isCallOrNewExpression(parent)) { var invocation = parent; - var list = void 0; - var argumentIndex = void 0; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a signature help session // 2. The token is either not associated with a list, or ends a list, so the session should end @@ -98343,32 +99642,12 @@ var ts; // Case 3: // foo(a#, #b#) -> The token is buried inside a list, and should give signature help // Find out if 'node' is an argument, a type argument, or neither - if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { - // Find the list that starts right *after* the < or ( token. - // If the user has just opened a list, consider this item 0. - list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); - ts.Debug.assert(list !== undefined); - argumentIndex = 0; - } - else { - // findListItemInfo can return undefined if we are not in parent's argument list - // or type argument list. This includes cases where the cursor is: - // - To the right of the closing parenthesis, non-substitution template, or template tail. - // - Between the type arguments and the arguments (greater than token) - // - On the target of the call (parent.func) - // - On the 'new' keyword in a 'new' expression - list = ts.findContainingList(node); - if (!list) - return undefined; - argumentIndex = getArgumentIndex(list, node); - } - var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; - var argumentCount = getArgumentCount(list); - if (argumentIndex !== 0) { - ts.Debug.assertLessThan(argumentIndex, argumentCount); - } - var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var info = getArgumentOrParameterListInfo(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos; + return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { // Check if we're actually inside the template; @@ -98376,6 +99655,7 @@ var ts; if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); } + return undefined; } else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { var templateExpression = parent; @@ -98404,7 +99684,7 @@ var ts; var attributeSpanStart = parent.attributes.pos; var attributeSpanEnd = ts.skipTrivia(sourceFile.text, parent.attributes.end, /*stopAfterLineBreak*/ false); return { - kind: 3 /* JSXAttributesArguments */, + isTypeParameterList: false, invocation: { kind: 0 /* Call */, node: parent }, argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart), argumentIndex: 0, @@ -98412,15 +99692,67 @@ var ts; }; } else { - var typeArgInfo = ts.isPossiblyTypeArgumentPosition(node, sourceFile); + var typeArgInfo = ts.getPossibleTypeArgumentsInfo(node, sourceFile); if (typeArgInfo) { var called = typeArgInfo.called, nTypeArguments = typeArgInfo.nTypeArguments; var invocation = { kind: 1 /* TypeArgs */, called: called }; var argumentsSpan = ts.createTextSpanFromBounds(called.getStart(sourceFile), node.end); - return { kind: 0 /* TypeArguments */, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; + return { isTypeParameterList: true, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; } + return undefined; } - return undefined; + } + function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) { + return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile); + } + function getHighestBinary(b) { + return ts.isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b; + } + function countBinaryExpressionParameters(b) { + return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2; + } + function tryGetParameterInfo(startingToken, _position, sourceFile, checker) { + var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker); + if (!info) + return undefined; + var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var signatures = contextualType.getCallSignatures(); + if (signatures.length !== 1) + return undefined; + var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(contextualType.symbol) }; + return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { + if (startingToken.kind !== 19 /* OpenParenToken */ && startingToken.kind !== 26 /* CommaToken */) + return undefined; + var parent = startingToken.parent; + switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + case 154 /* MethodDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + var info = getArgumentOrParameterListInfo(startingToken, sourceFile); + if (!info) + return undefined; + var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); + return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + case 202 /* BinaryExpression */: { + var highestBinary = getHighestBinary(parent); + var contextualType_1 = checker.getContextualType(highestBinary); + var argumentIndex_1 = startingToken.kind === 19 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; + var argumentCount_1 = countBinaryExpressionParameters(highestBinary); + return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) }; + } + default: + return undefined; + } + } + // The type of a function type node has a symbol at that node, but it's better to use the symbol for a parameter or type alias. + function chooseBetterSymbol(s) { + return s.name === "__type" /* Type */ + ? ts.firstDefined(s.declarations, function (d) { return ts.isFunctionTypeNode(d) ? d.parent.symbol : undefined; }) || s + : s; } function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may @@ -98497,7 +99829,7 @@ var ts; ts.Debug.assertLessThan(argumentIndex, argumentCount); } return { - kind: 2 /* TaggedTemplateArguments */, + isTypeParameterList: false, invocation: { kind: 0 /* Call */, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, @@ -98537,20 +99869,20 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile) { - var _loop_8 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker) { + var _loop_6 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); - var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); + var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker); if (argumentInfo) { return { value: argumentInfo }; } }; for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_8(n); - if (typeof state_4 === "object") - return state_4.value; + var state_2 = _loop_6(n); + if (typeof state_2 === "object") + return state_2.value; } return undefined; } @@ -98564,101 +99896,194 @@ var ts; return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { - var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; - var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.called; - var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); - var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); - var printer = ts.createPrinter({ removeComments: true }); - var items = candidates.map(function (candidateSignature) { - var signatureHelpParameters; - var prefixDisplayParts = []; - var suffixDisplayParts = []; - if (callTargetDisplayParts) { - ts.addRange(prefixDisplayParts, callTargetDisplayParts); - } - var isVariadic; - if (isTypeParameterList) { - isVariadic = false; // type parameter lists are not variadic - prefixDisplayParts.push(ts.punctuationPart(27 /* LessThanToken */)); - 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) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); - }); - ts.addRange(suffixDisplayParts, parameterParts); - } - else { - isVariadic = candidateSignature.hasRestParameter; - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); - printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); - } - }); - ts.addRange(prefixDisplayParts, typeParameterParts); - prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - signatureHelpParameters = ts.map(candidateSignature.parameters, createSignatureHelpParameterForParameter); - suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); - } - var returnTypeParts = ts.mapToDisplayParts(function (writer) { - writer.writePunctuation(":"); - writer.writeSpace(" "); - var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); - if (predicate) { - typeChecker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); - } - else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); - } - }); - ts.addRange(suffixDisplayParts, returnTypeParts); - return { - isVariadic: isVariadic, - prefixDisplayParts: prefixDisplayParts, - suffixDisplayParts: suffixDisplayParts, - separatorDisplayParts: [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()], - parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment(typeChecker), - tags: candidateSignature.getJsDocTags() - }; - }); + function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { + var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); + var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; + var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var selectedItemIndex = candidates.indexOf(resolvedSignature); ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; - function createSignatureHelpParameterForParameter(parameter) { - var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); - printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); - }); - return { - name: parameter.name, - documentation: parameter.getDocumentationComment(typeChecker), - displayParts: displayParts, - isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) - }; + } + function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { + var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; + var prefixDisplayParts = callTargetDisplayParts.concat(prefix); + var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; + var documentation = candidateSignature.getDocumentationComment(checker); + var tags = candidateSignature.getJsDocTags(); + return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) { + return ts.mapToDisplayParts(function (writer) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = checker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); + } + else { + checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); + } + }); + } + function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; + var printer = ts.createPrinter({ removeComments: true }); + var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var parameterParts = ts.mapToDisplayParts(function (writer) { + var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); + }); + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(27 /* LessThanToken */)], suffix: [ts.punctuationPart(29 /* GreaterThanToken */)].concat(parameterParts) }; + } + function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var isVariadic = candidateSignature.hasRestParameter; + var printer = ts.createPrinter({ removeComments: true }); + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); + } + }); + var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(19 /* OpenParenToken */)]), suffix: [ts.punctuationPart(20 /* CloseParenToken */)] }; + } + function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + } + function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + } + })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + var sourcemappedFileCache; + return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; } - function createSignatureHelpParameterForTypeParameter(typeParameter) { - var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); - }); - return { - name: typeParameter.symbol.name, - documentation: ts.emptyArray, - displayParts: displayParts, - isOptional: false - }; + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); + var comment = sourceMapCommentRegExp.exec(lineText); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!lineText.match(whitespaceOrMapCommentRegExp)) { + break; + } } } - })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + // swallow error + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + // obviously invalid map + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, getProgram(), sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function tryGetOriginalLocation(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); + return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + } + function tryGetGeneratedLocation(info) { + var program = getProgram(); + var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = ts.createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; })(ts || (ts = {})); /* @internal */ var ts; @@ -98666,6 +100091,7 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; + var checker = program.getDiagnosticsProducingTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { @@ -98680,8 +100106,8 @@ var ts; var name = importNameForConvertToDefaultImport(importNode); if (!name) continue; - var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + var module_1 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_1 && program.getSourceFile(module_1.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); } @@ -98696,8 +100122,8 @@ var ts; case 194 /* FunctionExpression */: var decl = ts.getDeclarationOfJSInitializer(node); if (decl) { - var symbol_2 = decl.symbol; - if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { + var symbol_1 = decl.symbol; + if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) { diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); break; } @@ -98725,6 +100151,9 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } + if (ts.isFunctionLikeDeclaration(node)) { + addConvertToAsyncFunctionDiagnostics(node, checker, diags); + } node.forEachChild(check); } } @@ -98765,9 +100194,56 @@ var ts; return undefined; } } + function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { + var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; + if (ts.isAsyncFunction(node) || !node.body || !functionType) { + return; + } + var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); + var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { + return; + } + // collect all the return statements + // check that a property access expression exists in there and that it is a handler + var returnStatements = getReturnStatementsWithPromiseHandlers(node); + if (returnStatements.length > 0) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } + /** @internal */ + function getReturnStatementsWithPromiseHandlers(node) { + var returnStatements = []; + if (ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + else { + visit(node); + } + function visit(child) { + if (ts.isFunctionLike(child)) { + return; + } + if (ts.isReturnStatement(child)) { + ts.forEachChild(child, addHandlers); + } + function addHandlers(returnChild) { + if (isPromiseHandler(returnChild)) { + returnStatements.push(child); + } + } + ts.forEachChild(child, visit); + } + return returnStatements; + } + ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + function isPromiseHandler(node) { + return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && + (node.expression.name.text === "then" || node.expression.name.text === "catch")); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -99485,7 +100961,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_7 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -99504,7 +100980,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_7(opt); } return options; } @@ -101104,7 +102580,6 @@ var ts; function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); - var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { @@ -101133,17 +102608,20 @@ var ts; var child = nodes[i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } - if (listEndToken !== 0 /* Unknown */) { - if (formattingScanner.isOnToken()) { - var tokenInfo = formattingScanner.readTokenInfo(parent); - // consume the list end token only if it is still belong to the parent - // there might be the case when current token matches end token but does not considered as one - // function (x: function) <-- - // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { - // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); - } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.readTokenInfo(parent); + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } } } @@ -101319,7 +102797,6 @@ var ts; // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; - var parts; if (startLine === endLine) { if (!firstLineIsIndented) { // treat as single line comment @@ -101327,18 +102804,18 @@ var ts; } return; } - else { - parts = []; - var startPos = commentRange.pos; - for (var line = startLine; line < endLine; line++) { - var endOfLine = ts.getEndLinePosition(line, sourceFile); - parts.push({ pos: startPos, end: endOfLine }); - startPos = ts.getStartPositionOfLine(line + 1, sourceFile); - } - if (indentFinalLine) { - parts.push({ pos: startPos, end: commentRange.end }); - } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); + } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); } + if (parts.length === 0) + return; var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); if (indentation === nonWhitespaceColumnInFirstPart.column) { @@ -101878,7 +103355,13 @@ var ts; getListIfStartEndIsInListRange(node.parent.parameters, start, end); } case 238 /* ClassDeclaration */: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 301 /* JSDocTemplateTag */: { + var typeParameters = node.parent.typeParameters; + return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end); + } case 190 /* NewExpression */: case 189 /* CallExpression */: { var start = node.getStart(sourceFile); @@ -102087,17 +103570,10 @@ var ts; function isControlFlowEndingStatement(kind, parent) { switch (kind) { case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: { - if (parent.kind !== 216 /* Block */) { - return true; - } - var grandParent = parent.parent; - // In a function, we may want to write inner functions after this. - return !(grandParent && grandParent.kind === 194 /* FunctionExpression */ || grandParent.kind === 237 /* FunctionDeclaration */); - } + case 232 /* ThrowStatement */: case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - return true; + return parent.kind !== 216 /* Block */; default: return false; } @@ -102257,7 +103733,7 @@ var ts; return this; }; ChangeTracker.prototype.delete = function (sourceFile, node) { - this.deletedNodes.push({ sourceFile: sourceFile, node: node, }); + this.deletedNodes.push({ sourceFile: sourceFile, node: node }); }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); @@ -102644,15 +104120,20 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_10 = function (sourceFile, node) { + var _loop_8 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { - deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + if (ts.isArray(node)) { + this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); + } + else { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } } }; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_10(sourceFile, node); + _loop_8(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -102702,14 +104183,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_11 = function (i) { + var _loop_9 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_11(i); + _loop_9(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -103015,21 +104496,9 @@ var ts; case 235 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 148 /* TypeParameter */: { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node.parent); - if (typeParameters.length === 1) { - var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; - var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1); - var nextToken = ts.getTokenAtPosition(sourceFile, end); - ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); - ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); - changes.deleteNodeRange(sourceFile, previousToken, nextToken); - } - else { - deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); - } + case 148 /* TypeParameter */: + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - } case 251 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { @@ -103609,6 +105078,442 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertToAsyncFunction"; + var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, + }); + function convertToAsyncFunction(changes, sourceFile, position, checker, context) { + // get the function declaration - returns a promise + var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + if (!functionToConvert) { + return; + } + var synthNamesMap = ts.createMap(); + var originalTypeMap = ts.createMap(); + var allVarNames = []; + var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); + var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + var constIdentifiers = getConstIdentifiers(synthNamesMap); + var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + if (!returnStatements.length) { + return; + } + // add the async keyword + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + function startTransformation(node, nodeToReplace) { + var newNodes = transformExpression(node, transformer, node); + changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); + } + var _loop_10 = function (statement) { + if (ts.isCallExpression(statement)) { + startTransformation(statement, statement); + } + else { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + }; + for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { + var statement = returnStatements_1[_i]; + _loop_10(statement); + } + } + // Returns the identifiers that are never reassigned in the refactor + function getConstIdentifiers(synthNamesMap) { + var constIdentifiers = []; + synthNamesMap.forEach(function (val) { + if (val.numberOfAssignmentsOriginal === 0) { + constIdentifiers.push(val.identifier); + } + }); + return constIdentifiers; + } + /* + Finds all of the expressions of promise type that should not be saved in a variable during the refactor + */ + function getAllPromiseExpressionsToReturn(func, checker) { + if (!func.body) { + return ts.createMap(); + } + var setOfExpressionsToReturn = ts.createMap(); + ts.forEachChild(func.body, function visit(node) { + if (isPromiseReturningExpression(node, checker, "then")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + ts.forEach(node.arguments, visit); + } + else if (isPromiseReturningExpression(node, checker, "catch")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned + ts.forEachChild(node, visit); + } + else if (isPromiseReturningExpression(node, checker)) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // don't recurse here, since we won't refactor any children or arguments of the expression + } + else { + ts.forEachChild(node, visit); + } + }); + return setOfExpressionsToReturn; + } + /* + Returns true if node is a promise returning expression + If name is not undefined, node is a promise returning call of name + */ + function isPromiseReturningExpression(node, checker, name) { + var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); + var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); + return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); + } + function declaredInFile(symbol, sourceFile) { + return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile; + } + /* + Renaming of identifiers may be neccesary as the refactor changes scopes - + This function collects all existing identifier names and names of identifiers that will be created in the refactor. + It then checks for any collisions and renames them through getSynthesizedDeepClone + */ + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { + var identsToRenameMap = ts.createMap(); // key is the symbol id + ts.forEachChild(nodeToRename, function visit(node) { + if (!ts.isIdentifier(node)) { + ts.forEachChild(node, visit); + return; + } + var symbol = checker.getSymbolAtLocation(node); + var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile); + if (symbol && isDefinedInFile) { + var type = checker.getTypeAtLocation(node); + var lastCallSignature = getLastCallSignature(type, checker); + var symbolIdString = ts.getSymbolId(symbol).toString(); + // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) + // Note - the choice of the last call signature is arbitrary + if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { + var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + synthNamesMap.set(symbolIdString, synthName); + allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + } + // we only care about identifiers that are parameters and declarations (don't care about other uses) + else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + // if the identifier name conflicts with a different identifier that we've already seen + if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { + var newName = getNewNameIfConflict(node, allVarNames); + identsToRenameMap.set(symbolIdString, newName.identifier); + synthNamesMap.set(symbolIdString, newName); + allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + } + else { + var identifier = ts.getSynthesizedDeepClone(node); + identsToRenameMap.set(symbolIdString, identifier); + synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); + if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { + allVarNames.push({ identifier: identifier, symbol: symbol }); + } + } + } + } + }); + return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback); + function isExpressionOrCallOnTypePromise(child) { + var node = child.parent; + if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) { + var nodeType = checker.getTypeAtLocation(node); + var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType); + return !!isPromise; + } + return false; + } + function deepCloneCallback(node, clone) { + if (ts.isIdentifier(node)) { + var symbol = checker.getSymbolAtLocation(node); + var symboldIdString = symbol && ts.getSymbolId(symbol).toString(); + var renameInfo = symbol && synthNamesMap.get(symboldIdString); + if (renameInfo) { + var type = checker.getTypeAtLocation(node); + if (type) { + originalType.set(ts.getNodeId(clone).toString(), type); + } + } + } + var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); + if (val !== undefined) { + setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString()); + setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val); + } + } + } + function getNewNameIfConflict(name, allVarNames) { + var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + var numberOfAssignmentsOriginal = 0; + var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); + return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + // dispatch function to recursively build the refactoring + function transformExpression(node, transformer, outermostParent, prevArgName) { + if (!node) { + return []; + } + var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); + var nodeType = originalType || transformer.checker.getTypeAtLocation(node); + if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformThen(node, transformer, outermostParent, prevArgName); + } + else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformCatch(node, transformer, prevArgName); + } + else if (ts.isPropertyAccessExpression(node)) { + return transformExpression(node.expression, transformer, outermostParent, prevArgName); + } + else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformPromiseCall(node, transformer, prevArgName); + } + return []; + } + function transformCatch(node, transformer, prevArgName) { + var func = node.arguments[0]; + var argName = getArgName(func, transformer); + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + /* + If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) + To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap + We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step + */ + if (prevArgName && !shouldReturn) { + prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block + transformer.synthNamesMap.forEach(function (val, key) { + if (val.identifier.text === prevArgName.identifier.text) { + transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + } + }); + // update the constIdentifiers list + if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { + transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + } + } + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); + var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); + var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); + /* + In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) + */ + var varDeclList; + if (prevArgName && !shouldReturn) { + var typeArray = prevArgName.types; + var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var varDecl = [ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)]; + varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); + } + var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); + return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; + } + function transformThen(node, transformer, outermostParent, prevArgName) { + var _a = node.arguments, res = _a[0], rej = _a[1]; + if (!res) { + return transformExpression(node.expression, transformer, outermostParent); + } + var argNameRes = getArgName(res, transformer); + var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); + if (rej) { + var argNameRej = getArgName(rej, transformer); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); + var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); + var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); + return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; + } + else { + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + } + return []; + } + function getFlagOfIdentifier(node, constIdentifiers) { + var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); + return inArr ? 2 /* Const */ : 1 /* Let */; + } + function transformPromiseCall(node, transformer, prevArgName) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call + var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; + var originalNodeParent = node.original ? node.original.parent : node.parent; + if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + } + else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return [ts.createStatement(ts.createAwait(node))]; + } + return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; + } + function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + } + return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + } + function getTransformationBody(func, prevArgName, argName, parent, transformer) { + var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; + var hasArgName = argName && argName.identifier.text.length > 0; + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); + switch (func.kind) { + case 71 /* Identifier */: + if (!hasArgName) + break; + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return ts.createNodeArray([ts.createReturn(synthCall)]); + } + if (!hasPrevArgName) + break; + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); + var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); + var returnType = callSignatures && callSignatures[0].getReturnType(); + var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); + prevArgName.types.push(returnType); + return varDeclOrAssignment; + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + // Arrow functions with block bodies { } will enter this control flow + if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + var refactoredStmts = []; + for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { + refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + } + else { + refactoredStmts.push(statement); + } + } + return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : + removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + } + else { + var funcBody = func.body; + var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); + var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); + if (innerCbBody.length > 0) { + return ts.createNodeArray(innerCbBody); + } + if (hasPrevArgName && !shouldReturn) { + var type_1 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); + var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); + prevArgName.types.push(returnType_1); + return varDeclOrAssignment_1; + } + else { + return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + } + } + break; + } + return ts.createNodeArray([]); + } + function getLastCallSignature(type, checker) { + var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); + return callSignatures && callSignatures[callSignatures.length - 1]; + } + function removeReturns(stmts, prevArgName, constIdentifiers) { + var ret = []; + for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { + var stmt = stmts_1[_i]; + if (ts.isReturnStatement(stmt)) { + if (stmt.expression) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + } + } + else { + ret.push(ts.getSynthesizedDeepClone(stmt)); + } + } + return ts.createNodeArray(ret); + } + function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { + var innerCbBody = []; + for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) { + var stmt = innerRetStmts_1[_i]; + ts.forEachChild(stmt, function visit(node) { + if (ts.isCallExpression(node)) { + var temp = transformExpression(node, transformer, node, prevArgName); + innerCbBody = innerCbBody.concat(temp); + if (innerCbBody.length > 0) { + return; + } + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + return innerCbBody; + } + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + function getArgName(funcNode, transformer) { + var numberOfAssignmentsOriginal = 0; + var types = []; + var name; + if (ts.isFunctionLikeDeclaration(funcNode)) { + if (funcNode.parameters.length > 0) { + var param = funcNode.parameters[0].name; + name = getMapEntryIfExists(param); + } + } + else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { + name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + else if (ts.isIdentifier(funcNode)) { + name = getMapEntryIfExists(funcNode); + } + if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { + return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + return name; + function getMapEntryIfExists(identifier) { + var originalNode = getOriginalNode(identifier); + var symbol = getSymbol(originalNode); + if (!symbol) { + return { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString()); + return mapEntry || { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + function getSymbol(node) { + return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node); + } + function getOriginalNode(node) { + return node.original ? node.original : node; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -104152,6 +106057,8 @@ var ts; var errorCodes = [ ts.Diagnostics.Cannot_find_name_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics.Cannot_find_namespace_0.code, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, @@ -104172,6 +106079,7 @@ var ts; var sourceFile = context.sourceFile, preferences = context.preferences; // Namespace fixes don't conflict, so just build a list. var addToNamespace = []; + var importType = []; // Keys are import clause node IDs. var addToExisting = ts.createMap(); // Keys are module specifiers. @@ -104186,7 +106094,10 @@ var ts; case 0 /* UseNamespace */: addToNamespace.push(fix); break; - case 1 /* AddToExisting */: { + case 1 /* ImportType */: + importType.push(fix); + break; + case 2 /* AddToExisting */: { var importClause = fix.importClause, importKind = fix.importKind; var key = String(ts.getNodeId(importClause)); var entry = addToExisting.get(key); @@ -104202,7 +106113,7 @@ var ts; } break; } - case 2 /* AddNew */: { + case 3 /* AddNew */: { var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; var entry = newImports.get(moduleSpecifier); if (!entry) { @@ -104229,15 +106140,19 @@ var ts; } }); return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var quotePreference = ts.getQuotePreference(sourceFile, preferences); for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { var fix = addToNamespace_1[_i]; addNamespaceQualifier(changes, sourceFile, fix); } + for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { + var fix = importType_1[_a]; + addImportType(changes, sourceFile, fix, quotePreference); + } addToExisting.forEach(function (_a) { var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); }); - var quotePreference = ts.getQuotePreference(sourceFile, preferences); newImports.forEach(function (imports, moduleSpecifier) { addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); }); @@ -104248,8 +106163,9 @@ var ts; var ImportFixKind; (function (ImportFixKind) { ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; - ImportFixKind[ImportFixKind["AddToExisting"] = 1] = "AddToExisting"; - ImportFixKind[ImportFixKind["AddNew"] = 2] = "AddNew"; + ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType"; + ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; })(ImportFixKind || (ImportFixKind = {})); var ImportKind; (function (ImportKind) { @@ -104258,12 +106174,12 @@ var ts; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, allSourceFiles, formatContext, symbolToken, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; - var fix = ts.first(getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences)); + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; } codefix.getImportCompletionAction = getImportCompletionAction; @@ -104278,22 +106194,25 @@ var ts; var exported = _a[_i]; if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ }); + result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); } } }); return result; } - function getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences) { + function isTypeOnlySymbol(s) { + return !(s.flags & 67216319 /* Value */); + } + function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); - var useNamespace = tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker); + var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports); // Don't bother providing an action to add a new import if we can add to an existing one. - var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences); + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences); return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); } - function tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker) { + function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { // It is possible that multiple import statements with the same specifier exist in the file. // e.g. // @@ -104306,13 +106225,13 @@ var ts; // 1. change "member3" to "ns.member3" // 2. add "member3" to the second import statement's import list // and it is up to the user to decide which one fits best. - return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; var namespace = getNamespaceImportName(declaration); if (namespace) { var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, symbolToken: symbolToken }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; } } }); @@ -104327,7 +106246,7 @@ var ts; return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) - ? { kind: 1 /* AddToExisting */, importClause: importClause, importKind: importKind } + ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } : undefined; }); } @@ -104340,27 +106259,31 @@ var ts; return declaration.name; } } - function getExistingImportDeclarations(_a, checker, _b) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var imports = _b.imports; - return ts.mapDefined(imports, function (moduleSpecifier) { + function getExistingImportDeclarations(_a, checker, sourceFile) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + // Can't use an es6 import for a type in JS. + return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } - function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { + function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { + var isJs = ts.isSourceFileJavaScript(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ kind: 2 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); + return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. + return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; + }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences) { + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, exportInfos, host, preferences); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); } function newImportInfoFromExistingSpecifier(_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -104369,13 +106292,13 @@ var ts; : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ ? declaration.moduleReference.expression : undefined; - return expression && ts.isStringLiteral(expression) ? { kind: 2 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; + return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; } function getFixesInfo(context, errorCode, pos) { var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) - : getFixesInfoForNonUMDImport(context, symbolToken); + : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined; return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); } function getFixesInfoForUMDImport(_a, token) { @@ -104386,8 +106309,8 @@ var ts; return undefined; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; - var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()) }]; - var fixes = getFixForImport(exportInfos, symbolName, token, program, sourceFile, host, preferences); + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -104425,21 +106348,18 @@ var ts; } function getFixesInfoForNonUMDImport(_a, symbolToken) { var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; - // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. var checker = program.getTypeChecker(); // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken - && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) ? checker.getJsxNamespace() - : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; - if (!symbolName) - return undefined; + : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */); var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences); + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } @@ -104449,7 +106369,7 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); @@ -104470,7 +106390,6 @@ var ts; return originalSymbolToExportInfos; } function getDefaultExportInfo(defaultExport, moduleSymbol, program) { - var checker = program.getTypeChecker(); var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -104478,12 +106397,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = checker.getAliasedSymbol(defaultExport); - return getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); } else { - var moduleName = moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target); - return moduleName === undefined ? undefined : { symbolForMeaning: defaultExport, name: moduleName }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; } } function getNameForExportDefault(symbol) { @@ -104511,18 +106429,21 @@ var ts; case 0 /* UseNamespace */: addNamespaceQualifier(changes, sourceFile, fix); return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; - case 1 /* AddToExisting */: { + case 1 /* ImportType */: + addImportType(changes, sourceFile, fix, quotePreference); + return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; + case 2 /* AddToExisting */: { var importClause = fix.importClause, importKind = fix.importKind; doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); - return [ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; + return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! } - case 2 /* AddNew */: { + case 3 /* AddNew */: { var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); - return [ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: return ts.Debug.assertNever(fix); @@ -104555,8 +106476,16 @@ var ts; } } function addNamespaceQualifier(changes, sourceFile, _a) { - var namespacePrefix = _a.namespacePrefix, symbolToken = _a.symbolToken; - changes.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken)); + var namespacePrefix = _a.namespacePrefix, position = _a.position; + changes.insertText(sourceFile, position, namespacePrefix + "."); + } + function addImportType(changes, sourceFile, _a, quotePreference) { + var moduleSpecifier = _a.moduleSpecifier, position = _a.position; + changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); + } + function getImportTypePrefix(moduleSpecifier, quotePreference) { + var quote = ts.getQuoteFromPreference(quotePreference); + return "import(" + quote + moduleSpecifier + quote + ")."; } function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; @@ -104645,6 +106574,8 @@ var ts; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, ]; codefix.registerCodeFix({ @@ -104684,7 +106615,7 @@ var ts; var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { - suggestion = checker.getSuggestionForNonexistentModule(node, resolvedSourceFile.symbol); + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); } } else { @@ -104743,16 +106674,16 @@ var ts; var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); if (!info) return undefined; - if (info.kind === InfoKind.enum) { + if (info.kind === 0 /* Enum */) { var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; } - var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); - var addMember = inJs ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic)) : - getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, parentDeclaration, token, makeStatic); + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, fixIds: [fixId], @@ -104760,76 +106691,76 @@ var ts; var program = context.program, preferences = context.preferences; var checker = program.getTypeChecker(); var seen = ts.createMap(); - var classToMembers = new ts.NodeMap(); + var typeDeclToMembers = new ts.NodeMap(); return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { codefix.eachDiagnostic(context, errorCodes, function (diag) { var info = getInfo(diag.file, diag.start, checker); if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { return; } - if (info.kind === InfoKind.enum) { + if (info.kind === 0 /* Enum */) { var token = info.token, parentDeclaration = info.parentDeclaration; addEnumMemberDeclaration(changes, checker, token, parentDeclaration); } else { var parentDeclaration = info.parentDeclaration, token_2 = info.token; - var infos = classToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; }); if (!infos.some(function (i) { return i.token.text === token_2.text; })) infos.push(info); } }); - classToMembers.forEach(function (infos, classDeclaration) { - var superClasses = getAllSuperClasses(classDeclaration, checker); - var _loop_12 = function (info) { + typeDeclToMembers.forEach(function (infos, classDeclaration) { + var supers = getAllSupers(classDeclaration, checker); + var _loop_11 = function (info) { // If some superclass added this property, don't add it again. - if (superClasses.some(function (superClass) { - var superInfos = classToMembers.get(superClass); + if (supers.some(function (superClassOrInterface) { + var superInfos = typeDeclToMembers.get(superClassOrInterface); return !!superInfos && superInfos.some(function (_a) { var token = _a.token; return token.text === info.token.text; }); })) return "continue"; - var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; // Always prefer to add a method declaration if possible. if (call) { - addMethodDeclaration(context, changes, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); } else { - if (inJs) { - addMissingMemberInJs(changes, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic); + if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token.text, makeStatic); } else { var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); - addPropertyDeclaration(changes, classDeclarationSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic); } } }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_12(info); + _loop_11(info); } }); })); }, }); - function getAllSuperClasses(cls, checker) { + function getAllSupers(decl, checker) { var res = []; - while (cls) { - var superElement = ts.getClassExtendsHeritageElement(cls); + while (decl) { + var superElement = ts.getClassExtendsHeritageElement(decl); var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); if (superDecl) { res.push(superDecl); } - cls = superDecl; + decl = superDecl; } return res; } var InfoKind; (function (InfoKind) { - InfoKind[InfoKind["enum"] = 0] = "enum"; - InfoKind[InfoKind["class"] = 1] = "class"; + InfoKind[InfoKind["Enum"] = 0] = "Enum"; + InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface"; })(InfoKind || (InfoKind = {})); function getInfo(tokenSourceFile, tokenPos, checker) { // The identifier of the missing property. eg: @@ -104846,33 +106777,34 @@ var ts; var symbol = leftExpressionType.symbol; if (!symbol || !symbol.declarations) return undefined; - var classDeclaration = ts.find(symbol.declarations, ts.isClassLike); - if (classDeclaration) { - var makeStatic = leftExpressionType.target !== checker.getDeclaredTypeOfSymbol(symbol); - var classDeclarationSourceFile = classDeclaration.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(classDeclarationSourceFile); + // Prefer to change the class instead of the interface if they are merged + var classOrInterface = ts.find(symbol.declarations, ts.isClassLike) || ts.find(symbol.declarations, ts.isInterfaceDeclaration); + if (classOrInterface) { + var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); + var declSourceFile = classOrInterface.getSourceFile(); + var inJs = ts.isSourceFileJavaScript(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); - return { kind: InfoKind.class, token: token, parentDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; + return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); if (enumDeclaration) { - return { kind: InfoKind.enum, token: token, parentDeclaration: enumDeclaration }; + return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration }; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); + function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { if (classDeclaration.kind === 207 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); - changeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization); + changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization); } else { var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); @@ -104880,32 +106812,32 @@ var ts; return; } var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); - changeTracker.insertNodeAtConstructorEnd(classDeclarationSourceFile, classConstructor, propertyInitialization); + changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization); } } function initializePropertyToUndefined(obj, propertyName) { return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); } - function getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic) { + function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) { var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); - var addProp = createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, token.text, typeNode); - return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, token.text, typeNode)]; + var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)]; } function getTypeNode(checker, classDeclaration, token) { var typeNode; if (token.parent.parent.kind === 202 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); // TODO: GH#18217 + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); } - function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } - function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, @@ -104913,10 +106845,10 @@ var ts; /*initializer*/ undefined); var lastProp = getNodeToInsertPropertyAfter(classDeclaration); if (lastProp) { - changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + changeTracker.insertNodeAfter(declSourceFile, lastProp, property); } else { - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property); } } // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. @@ -104930,7 +106862,7 @@ var ts; } return res; } - function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { + function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. var stringTypeNode = ts.createKeywordTypeNode(137 /* StringKeyword */); var indexingParameter = ts.createParameter( @@ -104942,22 +106874,22 @@ var ts; var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(context, changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences); + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); - if (containingMethodDeclaration && containingMethodDeclaration.parent === classDeclaration) { - changeTracker.insertNodeAfter(classDeclarationSourceFile, containingMethodDeclaration, methodDeclaration); + if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { + changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); } else { - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); + changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); } } function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { @@ -105256,6 +107188,7 @@ var ts; var fixName = "unusedIdentifier"; var fixIdPrefix = "unusedIdentifier_prefix"; var fixIdDelete = "unusedIdentifier_delete"; + var fixIdInfer = "unusedIdentifier_infer"; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics._0_is_declared_but_never_used.code, @@ -105263,6 +107196,7 @@ var ts; ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ts.Diagnostics.All_destructured_elements_are_unused.code, ts.Diagnostics.All_variables_are_unused.code, + ts.Diagnostics.All_type_parameters_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -105271,28 +107205,42 @@ var ts; var checker = program.getTypeChecker(); var sourceFiles = program.getSourceFiles(); var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (ts.isJSDocTemplateTag(token)) { + return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; + } + if (token.kind === 27 /* LessThanToken */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); + return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; + } var importDecl = tryGetFullImport(token); if (importDecl) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); - return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])]; } var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); }); if (delDestructure.length) { - return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)]; } var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); if (delVar.length) { - return [codefix.createCodeFixAction(fixName, delVar, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; } var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { - return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); - }); - if (deletion.length) { - var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; - result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); + if (token.kind === 126 /* InferKeyword */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); + var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; + result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); + } + else { + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); + if (deletion.length) { + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + } } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { @@ -105300,7 +107248,7 @@ var ts; } return result; }, - fixIds: [fixIdPrefix, fixIdDelete], + fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program; var checker = program.getTypeChecker(); @@ -105309,27 +107257,47 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, diag.start); switch (context.fixId) { case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); - } + tryPrefixDeclaration(changes, diag.code, sourceFile, token); break; case fixIdDelete: { + if (token.kind === 126 /* InferKeyword */) + break; // Can't delete var importDecl = tryGetFullImport(token); if (importDecl) { changes.delete(sourceFile, importDecl); } + else if (ts.isJSDocTemplateTag(token)) { + changes.delete(sourceFile, token); + } + else if (token.kind === 27 /* LessThanToken */) { + deleteTypeParameters(changes, sourceFile, token); + } else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && !tryDeleteFullVariableStatement(sourceFile, token, changes)) { tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); } break; } + case fixIdInfer: + if (token.kind === 126 /* InferKeyword */) { + changeInferToUnknown(changes, sourceFile, token); + } + break; default: ts.Debug.fail(JSON.stringify(context.fixId)); } }); }, }); + function changeInferToUnknown(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(142 /* UnknownKeyword */)); + } + function createDeleteFix(changes, diag) { + return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); + } + function deleteTypeParameters(changes, sourceFile, token) { + changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters)); + } // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(token) { return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; @@ -105356,13 +107324,19 @@ var ts; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { // Don't offer to prefix a property. - if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) { + if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) + return; + if (token.kind === 126 /* InferKeyword */) { + token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; + } + if (ts.isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); } } function canPrefix(token) { switch (token.parent.kind) { case 149 /* Parameter */: + case 148 /* TypeParameter */: return true; case 235 /* VariableDeclaration */: { var varDecl = token.parent; @@ -105453,69 +107427,54 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, }); - function doChange(changes, sourceFile, start) { + function doChange(changes, sourceFile, start, length) { var token = ts.getTokenAtPosition(sourceFile, start); var statement = ts.findAncestor(token, ts.isStatement); ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; - switch (container.kind) { - case 220 /* IfStatement */: - if (container.elseStatement) { - if (ts.isBlock(statement.parent)) { - changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); - } - else { - changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 220 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; } - break; - } - // falls through - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - changes.delete(sourceFile, container); - break; - default: - if (ts.isBlock(statement.parent)) { - split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); - } - else { - changes.delete(sourceFile, statement); - } + // falls through + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } } - } - function shouldRemove(s) { - // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && - // `var x;` may declare a variable used above - !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); - } - function isPurelyTypeDeclaration(s) { - switch (s.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - return true; - case 242 /* ModuleDeclaration */: - return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; - case 241 /* EnumDeclaration */: - return ts.hasModifier(s, 2048 /* Const */); - default: - return false; + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); } } - function sliceAfter(arr, value) { - var index = arr.indexOf(value); - ts.Debug.assert(index !== -1); - return arr.slice(index); - } - // Calls 'cb' with the start and end of each range where 'pred' is true. - function split(arr, pred, cb) { - ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); }); + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -105849,7 +107808,7 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences) { + function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { @@ -105874,7 +107833,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences)); + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -106390,7 +108349,7 @@ var ts; return; } else { - var indexType = checker.getTypeAtLocation(parent); + var indexType = checker.getTypeAtLocation(parent.argumentExpression); var indexUsageContext = {}; inferTypeFromContext(parent, checker, indexUsageContext); if (indexType.flags & 168 /* NumberLike */) { @@ -106448,10 +108407,10 @@ var ts; } } if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); // TODO: GH#18217 + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); } return checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 } @@ -106571,7 +108530,7 @@ var ts; return getImportCodeFixesForExpression(context, node); } function getImportCodeFixesForExpression(context, expr) { - var type = context.program.getTypeChecker().getTypeAtLocation(expr); // TODO: GH#18217 + var type = context.program.getTypeChecker().getTypeAtLocation(expr); if (!(type.symbol && type.symbol.originatingImport)) { return []; } @@ -107153,7 +109112,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_13 = function (element) { + var _loop_12 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -107172,7 +109131,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_13(element); + _loop_12(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -107906,8 +109865,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), // TODO: GH#18217 - scope, 1 /* NoTruncation */); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -108212,7 +110170,7 @@ var ts; return scope.members; } else { - ts.assertTypeIsNever(scope); + ts.assertType(scope); } return ts.emptyArray; } @@ -108334,7 +110292,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { // TODO: GH#18217 + else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -108405,7 +110363,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_14 = function (i) { + var _loop_13 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -108445,7 +110403,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_14(i); + _loop_13(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -108467,7 +110425,7 @@ var ts; function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1 /* Read */; } if (inGenericContext) { - var type = checker.getTypeAtLocation(node); // TODO: GH#18217 + var type = checker.getTypeAtLocation(node); recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { @@ -108995,10 +110953,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_15 = function (sourceFile) { + var _loop_14 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_16 = function (statement) { + var _loop_15 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -109020,12 +110978,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_16(statement); + _loop_15(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_15(sourceFile); + _loop_14(sourceFile); } } function getNamespaceLikeImport(node) { @@ -109140,9 +111098,9 @@ var ts; if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { - var exports = addExport(statement, useEs6Exports); - if (exports) - return exports; + var exports_1 = addExport(statement, useEs6Exports); + if (exports_1) + return exports_1; } return statement; }); @@ -109170,7 +111128,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -109701,7 +111659,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 302 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 303 /* LastJSDocNode */; }); return child.kind < 146 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -109771,7 +111729,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(303 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(304 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { @@ -110017,8 +111975,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -110501,7 +112459,6 @@ var ts; if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } - var sourcemappedFileCache; function log(message) { if (host.log) { host.log(message); @@ -110509,6 +112466,7 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -110606,7 +112564,7 @@ var ts; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during // the course of whatever called `synchronizeHostData` - sourcemappedFileCache = ts.createSourceFileLikeCache(host); + sourceMapper.clearCache(); // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); @@ -110755,31 +112713,15 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - // Try getting just type at this position and show - switch (node.kind) { - case 71 /* Identifier */: - if (ts.isLabelName(node)) { - // Type here will be 'any', avoid displaying this. - return undefined; - } - // falls through - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 97 /* SuperKeyword */: - // For the identifiers/this/super etc get the type at position - var type_1 = typeChecker.getTypeAtLocation(node); - return type_1 && { - kind: "" /* unknown */, - kindModifiers: "" /* none */, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_1, ts.getContainerNode(node)); }), - documentation: type_1.symbol ? type_1.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_1.symbol ? type_1.symbol.getJsDocTags() : undefined - }; - } - return undefined; + var type_2 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_2 && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(node)); }), + documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined + }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); @@ -110793,177 +112735,39 @@ var ts; tags: 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); - var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); - if (property) { - return property; - } - } - return checker.getSymbolAtLocation(node); - } - function toLineColumnOffset(fileName, position) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 - return file.getLineAndCharacterOfPosition(position); - } - // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) - var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/; - var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; - var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); - if (!mappedFile) { - return; - } - var starts = ts.getLineStarts(mappedFile); - for (var index = starts.length - 1; index >= 0; index--) { - var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); - var comment = sourceMapCommentRegExp.exec(lineText); - if (comment) { - return comment[1]; - } - // If we see a nonwhitespace/map comment-like line, break, to avoid scanning up the entire file - else if (!lineText.match(whitespaceOrMapCommentRegExp)) { - break; - } - } - } - function convertDocumentToSourceMapper(file, contents, mapFileName) { - var maps; - try { - maps = JSON.parse(contents); - } - catch (_a) { - // swallow error - } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { - // obviously invalid map - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - return file.sourceMapper = ts.sourcemaps.decode({ - readFile: function (s) { return host.readFile(s); }, - fileExists: function (s) { return host.fileExists(s); }, - getCanonicalFileName: getCanonicalFileName, - log: log, - }, mapFileName, maps, program, sourcemappedFileCache); - } - function getSourceMapper(fileName, file) { - if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - if (file.sourceMapper) { - return file.sourceMapper; - } - var mapFileName = scanForSourcemapURL(fileName); - if (mapFileName) { - var match = base64UrlRegExp.exec(mapFileName); - if (match) { - if (match[1]) { - var base64Object = match[1]; - return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); - } - // Not a data URL we can parse, skip it - mapFileName = undefined; - } - } - var possibleMapLocations = []; - if (mapFileName) { - possibleMapLocations.push(mapFileName); - } - possibleMapLocations.push(fileName + ".map"); - for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { - var location = possibleMapLocations_1[_i]; - var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); - if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 - } - } - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - function makeGetTargetOfMappedPosition(extract, create) { - return getTargetOfMappedPosition; - function getTargetOfMappedPosition(input, original) { - if (original === void 0) { original = input; } - var info = extract(input); - if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { - var file = program.getSourceFile(info.fileName); - if (!file) { - var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); - file = sourcemappedFileCache.get(path); - } - if (!file) { - return input; - } - var mapper = getSourceMapper(info.fileName, file); - var newLoc = mapper.getOriginalPosition(info); - if (newLoc === info) - return input; - return getTargetOfMappedPosition(create(newLoc, input, original), original); - } - return input; + function shouldGetType(sourceFile, node, position) { + switch (node.kind) { + case 71 /* Identifier */: + return !ts.isLabelName(node); + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: + // Don't return quickInfo if inside the comment in `a/**/.b` + return !ts.isInComment(sourceFile, position); + case 99 /* ThisKeyword */: + case 176 /* ThisType */: + case 97 /* SuperKeyword */: + return true; + default: + return false; } } - var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({ - containerKind: info.containerKind, - containerName: info.containerName, - fileName: newLoc.fileName, - kind: info.kind, - name: info.name, - textSpan: { - start: newLoc.position, - length: info.textSpan.length - }, - originalFileName: original.fileName, - originalTextSpan: original.textSpan - }); }); - function getTargetOfMappedDeclarationFiles(infos) { - return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); }); - } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position)); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } function getDefinitionAndBoundSpan(fileName, position) { synchronizeHostData(); - var result = ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); - if (!result) - return result; - var mappedDefs = getTargetOfMappedDeclarationFiles(result.definitions); - if (mappedDefs === result.definitions) { - return result; - } - return { - definitions: mappedDefs, - textSpan: result.textSpan - }; + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position)); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } /// Goto implementation - var getTargetOfMappedImplementationLocation = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ - fileName: newLoc.fileName, - kind: info.kind, - displayParts: info.displayParts, - textSpan: { - start: newLoc.position, - length: info.textSpan.length - }, - originalFileName: info.fileName, - originalTextSpan: info.textSpan - }); }); - function getTargetOfMappedImplementationLocations(infos) { - return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); }); - } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedImplementationLocations(ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position)); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -110976,7 +112780,8 @@ var ts; }); }); }); } function getDocumentHighlights(fileName, position, filesToSearch) { - ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === fileName; })); + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); var sourceFile = getValidSourceFile(fileName); @@ -111014,7 +112819,6 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } - /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); @@ -111214,7 +113018,7 @@ var ts; } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } - return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences); + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -111270,10 +113074,15 @@ var ts; return undefined; var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent : ts.isJsxText(token) ? token.parent : undefined; - if (element && !ts.tagNamesAreEquivalent(element.openingElement.tagName, element.closingElement.tagName)) { + if (element && isUnclosedTag(element)) { return { newText: "" }; } } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); @@ -111484,7 +113293,8 @@ var ts; getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, - toLineColumnOffset: toLineColumnOffset + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, }; } ts.createLanguageService = createLanguageService; @@ -111500,7 +113310,7 @@ var ts; function initializeNameTable(sourceFile) { var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteral(node) && literalIsName(node)) { + if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { var text = ts.getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } @@ -111530,6 +113340,11 @@ var ts; */ /* @internal */ function getContainingObjectLiteralElement(node) { + var element = getContainingObjectLiteralElementWorker(node); + return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined; + } + ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; + function getContainingObjectLiteralElementWorker(node) { switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -111544,37 +113359,40 @@ var ts; } return undefined; } - ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; - /* @internal */ - function getPropertySymbolsFromContextualType(typeChecker, node) { - var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); // TODO: GH#18217 - return getPropertySymbolsFromType(contextualType, node.name); // TODO: GH#18217 + function getSymbolAtLocationForQuickInfo(node, checker) { + var object = getContainingObjectLiteralElement(node); + if (object) { + var contextualType = checker.getContextualType(object.parent); + var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); + if (properties && properties.length === 1) { + return ts.first(properties); + } + } + return checker.getSymbolAtLocation(node); } - ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + /** Gets all symbols for one property. Does not get symbols for every property. */ /* @internal */ - function getPropertySymbolsFromType(type, propName) { - var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); - if (name && type) { - var result_2 = []; - var symbol = type.getProperty(name); - if (type.flags & 262144 /* Union */) { - ts.forEach(type.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_2.push(symbol); - } - }); - return result_2; - } - if (symbol) { - result_2.push(symbol); - return result_2; - } + function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + if (!contextualType.isUnion()) { + var symbol = contextualType.getProperty(name); + return symbol ? [symbol] : ts.emptyArray; } - return undefined; + var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); }); + if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { + var symbol = contextualType.getProperty(name); + if (symbol) + return [symbol]; + } + if (discriminatedPropertySymbols.length === 0) { + // Bad discriminant -- do again without discriminating + return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }); + } + return discriminatedPropertySymbols; } - ts.getPropertySymbolsFromType = getPropertySymbolsFromType; + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; function isArgumentOfElementAccessExpression(node) { return node && node.parent && @@ -112342,7 +114160,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { var encoded = this.shimHost.getScriptFileNames(); - return this.files = JSON.parse(encoded); + return JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); @@ -113674,6 +115492,7 @@ var ts; CommandTypes["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full"; CommandTypes["Implementation"] = "implementation"; CommandTypes["ImplementationFull"] = "implementation-full"; + CommandTypes["EmitOutput"] = "emit-output"; CommandTypes["Exit"] = "exit"; CommandTypes["Format"] = "format"; CommandTypes["Formatonkey"] = "formatonkey"; @@ -113793,9 +115612,10 @@ var ts; var server; (function (server) { var TextStorage = (function () { - function TextStorage(host, fileName, initialVersion) { + function TextStorage(host, fileName, initialVersion, info) { this.host = host; this.fileName = fileName; + this.info = info; this.version = initialVersion || { svc: 0, text: 0 }; } TextStorage.prototype.getVersion = function () { @@ -113875,7 +115695,21 @@ var ts; return this.svc.positionToLineOffset(position); }; TextStorage.prototype.getFileText = function (tempFileName) { - return this.host.readFile(tempFileName || this.fileName) || ""; + var _this = this; + var text; + var fileName = tempFileName || this.fileName; + var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; + if (!ts.hasTypeScriptFileExtension(this.fileName)) { + var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; + if (fileSize > server.maxFileSize) { + ts.Debug.assert(!!this.info.containingProjects.length); + var service = this.info.containingProjects[0].projectService; + service.logger.info("Skipped loading contents of large file " + fileName + " for info " + this.info.fileName + ": fileSize: " + fileSize); + this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); + return ""; + } + } + return getText(); }; TextStorage.prototype.switchToScriptVersionCache = function () { if (!this.svc || this.pendingReloadFromDisk) { @@ -113920,7 +115754,7 @@ var ts; this.path = path; this.containingProjects = []; this.isDynamic = isDynamicFileName(fileName); - this.textStorage = new TextStorage(host, fileName, initialVersion); + this.textStorage = new TextStorage(host, fileName, initialVersion, this); if (hasMixedContent || this.isDynamic) { this.textStorage.reload(""); this.realpath = this.path; @@ -114099,12 +115933,15 @@ var ts; if (this.isDynamicOrHasMixedContent()) { this.textStorage.reload(""); this.markContainingProjectsAsDirty(); + return true; } else { if (this.textStorage.reloadWithFileText(tempFileName)) { this.markContainingProjectsAsDirty(); + return true; } } + return false; }; ScriptInfo.prototype.getLineInfo = function (line) { return this.textStorage.getLineInfo(line); @@ -114358,11 +116195,11 @@ var ts; this.projectService.pendingEnsureProjectForOpenFiles = true; } Project.prototype.isNonTsProject = function () { - this.updateGraph(); + server.updateProjectIfDirty(this); return allFilesAreJsOrDts(this); }; Project.prototype.isJsOnlyProject = function () { - this.updateGraph(); + server.updateProjectIfDirty(this); return hasOneOrMoreJsAndNoTsFiles(this); }; Project.resolveModule = function (moduleName, initialDir, host, log) { @@ -114402,7 +116239,7 @@ var ts; return this.projectStateVersion.toString(); }; Project.prototype.getProjectReferences = function () { - return undefined; + return server.emptyArray; }; Project.prototype.getScriptFileNames = function () { var _this = this; @@ -114526,10 +116363,13 @@ var ts; Project.prototype.getLanguageService = function (ensureSynchronized) { if (ensureSynchronized === void 0) { ensureSynchronized = true; } if (ensureSynchronized) { - this.updateGraph(); + server.updateProjectIfDirty(this); } return this.languageService; }; + Project.prototype.getSourceMapper = function () { + return this.getLanguageService().getSourceMapper(); + }; Project.prototype.shouldEmitFile = function (scriptInfo) { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); }; @@ -114538,7 +116378,7 @@ var ts; if (!this.languageServiceEnabled) { return []; } - this.updateGraph(); + server.updateProjectIfDirty(this); this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; @@ -114618,10 +116458,19 @@ var ts; var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } + var projectReferences = this.program.getProjectReferences(); + if (projectReferences) { + for (var _b = 0, projectReferences_1 = projectReferences; _b < projectReferences_1.length; _b++) { + var ref = projectReferences_1[_b]; + if (ref) { + this.detachScriptInfoFromProject(ref.sourceFile.fileName); + } + } + } } ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); - for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { - var root = _c[_b]; + for (var _c = 0, _d = this.rootFiles; _c < _d.length; _c++) { + var root = _d[_c]; root.detachFromProject(this); } this.projectService.pendingEnsureProjectForOpenFiles = true; @@ -114738,7 +116587,7 @@ var ts; return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); }; Project.prototype.containsFile = function (filename, requireOpen) { - var info = this.projectService.getScriptInfoForPath(this.toPath(filename)); + var info = this.projectService.getScriptInfoForNormalizedPath(filename); if (info && (info.isScriptOpen() || !requireOpen)) { return this.containsScriptInfo(info); } @@ -114963,7 +116812,7 @@ var ts; } }; Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - this.updateGraph(); + server.updateProjectIfDirty(this); var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -115197,11 +117046,15 @@ var ts; return server.asNormalizedPath(this.getProjectName()); }; ConfiguredProject.prototype.getProjectReferences = function () { - return this.projectReferences; + return this.projectReferences || server.emptyArray; }; ConfiguredProject.prototype.updateReferences = function (refs) { this.projectReferences = refs; }; + ConfiguredProject.prototype.getResolvedProjectReferences = function () { + var program = this.getCurrentProgram(); + return program && program.getProjectReferences(); + }; ConfiguredProject.prototype.enablePlugins = function () { var host = this.projectService.host; var options = this.getCompilationSettings(); @@ -115324,7 +117177,9 @@ var ts; var server; (function (server) { server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + server.maxFileSize = 4 * 1024 * 1024; server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; server.ProjectInfoTelemetryEvent = "projectInfo"; @@ -115464,12 +117319,16 @@ var ts; ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); + function isOpenScriptInfo(infoOrFileName) { + return !!infoOrFileName.containingProjects; + } function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } + server.updateProjectIfDirty = updateProjectIfDirty; var ProjectService = (function () { function ProjectService(opts) { var _this = this; @@ -115628,7 +117487,7 @@ var ts; this.pendingProjectUpdates.set(projectName, project); this.throttledOperations.schedule(projectName, 250, function () { if (_this.pendingProjectUpdates.delete(projectName)) { - project.updateGraph(); + updateProjectIfDirty(project); } }); }; @@ -115648,6 +117507,16 @@ var ts; }; this.eventHandler(event); }; + ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.LargeFileReferencedEvent, + data: { file: file, fileSize: fileSize, maxFileSize: server.maxFileSize } + }; + this.eventHandler(event); + }; ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { this.delayUpdateProjectGraph(project); this.delayEnsureProjectForOpenFiles(); @@ -115695,13 +117564,17 @@ var ts; return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); }; ProjectService.prototype.forEachProject = function (cb) { - for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { - var p = _a[_i]; - cb(p); - } + this.inferredProjects.forEach(cb); this.configuredProjects.forEach(cb); this.externalProjects.forEach(cb); }; + ProjectService.prototype.forEachEnabledProject = function (cb) { + this.forEachProject(function (project) { + if (!project.isOrphan() && project.languageServiceEnabled) { + cb(project); + } + }); + }; ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) { return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName); }; @@ -115916,15 +117789,17 @@ var ts; ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { - if (!configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file"); } return configFileExistenceInfo.exists; } - var openFilesImpactedByConfigFile = ts.createMap(); - openFilesImpactedByConfigFile.set(info.path, false); var exists = this.host.fileExists(configFileName); + var openFilesImpactedByConfigFile = ts.createMap(); + if (isOpenScriptInfo(info)) { + openFilesImpactedByConfigFile.set(info.path, false); + } configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile }; this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file"); @@ -116054,7 +117929,7 @@ var ts; if (this.syntaxOnly) { return undefined; } - ts.Debug.assert(this.openFiles.has(info.path)); + ts.Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path)); var projectRootPath = this.openFiles.get(info.path); var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); }; @@ -116081,7 +117956,8 @@ var ts; }; ProjectService.prototype.getConfigFileNameForFile = function (info) { var _this = this; - ts.Debug.assert(info.isScriptOpen()); + if (isOpenScriptInfo(info)) + ts.Debug.assert(info.isScriptOpen()); this.logger.info("Search path: " + ts.getDirectoryPath(info.fileName)); var configFileName = this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { return _this.configFileExists(configFileName, canonicalConfigFilePath, info); @@ -116358,9 +118234,11 @@ var ts; if (!this.eventHandler || this.suppressDiagnosticEvents) { return; } + var diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); + diagnostics.push.apply(diagnostics, project.getAllProjectErrors()); this.eventHandler({ eventName: server.ConfigFileDiagEvent, - data: { configFileName: project.getConfigFilePath(), diagnostics: project.getAllProjectErrors(), triggerFile: triggerFile } + data: { configFileName: project.getConfigFilePath(), diagnostics: diagnostics, triggerFile: triggerFile } }); }; ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { @@ -116429,6 +118307,14 @@ var ts; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; + ProjectService.prototype.getScriptInfoOrConfig = function (uncheckedFileName) { + var path = server.toNormalizedPath(uncheckedFileName); + var info = this.getScriptInfoForNormalizedPath(path); + if (info) + return info; + var configProject = this.configuredProjects.get(uncheckedFileName); + return configProject && configProject.getCompilerOptions().configFile; + }; ProjectService.prototype.getSymlinkedProjects = function (info) { var projects; if (this.realpathToScriptInfos) { @@ -116630,9 +118516,42 @@ var ts; ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); }; + ProjectService.prototype.getOriginalLocationEnsuringConfiguredProject = function (project, location) { + var originalLocation = project.getSourceMapper().tryGetOriginalLocation(location); + if (!originalLocation) + return undefined; + var fileName = originalLocation.fileName; + if (!this.getScriptInfo(fileName) && !this.host.fileExists(fileName)) + return undefined; + var originalFileInfo = { fileName: server.toNormalizedPath(fileName), path: this.toPath(fileName) }; + var configFileName = this.getConfigFileNameForFile(originalFileInfo); + if (!configFileName) + return undefined; + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + updateProjectIfDirty(configuredProject); + addOriginalConfiguredProject(configuredProject); + var originalScriptInfo = this.getScriptInfo(fileName); + if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) + return undefined; + originalScriptInfo.containingProjects.forEach(function (project) { + if (project.projectKind === server.ProjectKind.Configured) { + addOriginalConfiguredProject(project); + } + }); + return originalLocation; + function addOriginalConfiguredProject(originalProject) { + if (!project.originalConfiguredProjects) { + project.originalConfiguredProjects = ts.createMap(); + } + project.originalConfiguredProjects.set(originalProject.canonicalConfigFilePath, true); + } + }; + ProjectService.prototype.fileExists = function (fileName) { + return this.filenameToScriptInfo.has(fileName) || this.host.fileExists(fileName); + }; ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) { return ts.find(this.externalProjects, function (proj) { - proj.updateGraph(); + updateProjectIfDirty(proj); return proj.containsScriptInfo(info); }); }; @@ -116667,11 +118586,7 @@ var ts; this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); } ts.Debug.assert(!info.isOrphan()); - this.configuredProjects.forEach(function (project) { - if (!project.hasOpenRef()) { - _this.removeProject(project); - } - }); + this.removeOrphanConfiguredProjects(); for (var _i = 0, _a = this.inferredProjects.slice(); _i < _a.length; _i++) { var inferredProject = _a[_i]; if (inferredProject.isOrphan()) { @@ -116688,6 +118603,38 @@ var ts; this.telemetryOnOpenFile(info); return { configFileName: configFileName, configFileErrors: configFileErrors }; }; + ProjectService.prototype.removeOrphanConfiguredProjects = function () { + var _this = this; + var toRemoveConfiguredProjects = ts.cloneMap(this.configuredProjects); + this.inferredProjects.forEach(markOriginalProjectsAsUsed); + this.externalProjects.forEach(markOriginalProjectsAsUsed); + this.configuredProjects.forEach(function (project) { + if (project.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + markOriginalProjectsAsUsed(project); + } + else { + var resolvedProjectReferences = project.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var ref = resolvedProjectReferences_1[_i]; + if (ref) { + var refProject = _this.configuredProjects.get(ref.sourceFile.path); + if (refProject && refProject.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + } + } + } + } + } + }); + toRemoveConfiguredProjects.forEach(function (project) { return _this.removeProject(project); }); + function markOriginalProjectsAsUsed(project) { + if (!project.isOrphan() && project.originalConfiguredProjects) { + project.originalConfiguredProjects.forEach(function (_value, configuredProjectPath) { return toRemoveConfiguredProjects.delete(configuredProjectPath); }); + } + } + }; ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) { if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { return; @@ -117013,6 +118960,10 @@ var ts; return ProjectService; }()); server.ProjectService = ProjectService; + function isConfigFile(config) { + return config.kind !== undefined; + } + server.isConfigFile = isConfigFile; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -117037,25 +118988,6 @@ var ts; } return false; } - function compareNumber(a, b) { - return a - b; - } - function compareFileStart(a, b) { - if (a.file < b.file) { - return -1; - } - else if (a.file === b.file) { - var n = compareNumber(a.start.line, b.start.line); - if (n === 0) { - return compareNumber(a.start.offset, b.start.offset); - } - else - return n; - } - else { - return 1; - } - } function formatDiag(fileName, project, diag) { var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); return { @@ -117205,12 +119137,9 @@ var ts; }; } server.toEvent = toEvent; - function isProjectsArray(projects) { - return !!projects.length; - } function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { - var outputs = ts.flatMap(isProjectsArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); - if (!isProjectsArray(projects) && projects.symLinkedProjects) { + var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { var value = getValue(path); outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); @@ -117220,6 +119149,150 @@ var ts; ? ts.sortAndDeduplicate(outputs, comparer, areEqual) : ts.deduplicate(outputs, areEqual); } + function combineProjectOutputFromEveryProject(projectService, action, areEqual) { + var outputs = []; + projectService.forEachEnabledProject(function (project) { + var theseOutputs = action(project); + outputs.push.apply(outputs, theseOutputs.filter(function (output) { return !outputs.some(function (o) { return areEqual(o, output); }); })); + }); + return outputs; + } + function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, projectService, action, getLocation, resultsEqual) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, undefined, projectService, function (_a, tryAddToTodo) { + var project = _a.project; + for (var _i = 0, _b = action(project); _i < _b.length; _i++) { + var output = _b[_i]; + if (!ts.contains(outputs, output, resultsEqual) && !tryAddToTodo(project, getLocation(output))) { + outputs.push(output); + } + } + }, undefined); + return outputs; + } + function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, projectService, findInStrings, findInComments) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + var project = _a.project, location = _a.location; + for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.position, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { + var output = _b[_i]; + if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { + outputs.push(output); + } + } + }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); + return outputs; + } + function getDefinitionLocation(defaultProject, initialLocation) { + var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.position); + var info = infos && ts.firstOrUndefined(infos); + return info && { fileName: info.fileName, position: info.textSpan.start }; + } + function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + var project = _a.project, location = _a.location; + var _loop_8 = function (outputReferencedSymbol) { + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + if (!symbolToAddTo) { + symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + outputs.push(symbolToAddTo); + } + for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + symbolToAddTo.references.push(ref); + } + } + }; + for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.position) || server.emptyArray; _i < _b.length; _i++) { + var outputReferencedSymbol = _b[_i]; + _loop_8(outputReferencedSymbol); + } + }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); + return outputs.filter(function (o) { return o.references.length !== 0; }); + } + function forEachProjectInProjects(projects, path, cb) { + for (var _i = 0, _a = ts.isArray(projects) ? projects : projects.projects; _i < _a.length; _i++) { + var project = _a[_i]; + cb(project, path); + } + if (!ts.isArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (symlinkedProjects, symlinkedPath) { + for (var _i = 0, symlinkedProjects_1 = symlinkedProjects; _i < symlinkedProjects_1.length; _i++) { + var project = symlinkedProjects_1[_i]; + cb(project, symlinkedPath); + } + }); + } + } + function combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, cb, getDefinition) { + var toDo; + var seenProjects = ts.createMap(); + forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { + var location = (initialLocation ? { fileName: path, position: initialLocation.position } : undefined); + toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb); + }); + if (getDefinition) { + var memGetDefinition_1 = ts.memoize(getDefinition); + projectService.forEachEnabledProject(function (project) { + if (!ts.addToSeen(seenProjects, project.projectName)) + return; + var definition = getDefinitionInProject(memGetDefinition_1(), defaultProject, project); + if (definition) { + toDo = callbackProjectAndLocation({ project: project, location: definition }, projectService, toDo, seenProjects, cb); + } + }); + } + while (toDo && toDo.length) { + toDo = callbackProjectAndLocation(ts.Debug.assertDefined(toDo.pop()), projectService, toDo, seenProjects, cb); + } + } + function getDefinitionInProject(definition, definingProject, project) { + if (!definition || project.containsFile(server.toNormalizedPath(definition.fileName))) + return definition; + var mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedLocation(definition); + return mappedDefinition && project.containsFile(server.toNormalizedPath(mappedDefinition.fileName)) ? mappedDefinition : undefined; + } + function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) { + if (projectAndLocation.project.getCancellationToken().isCancellationRequested()) + return undefined; + cb(projectAndLocation, function (project, location) { + seenProjects.set(projectAndLocation.project.projectName, true); + var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); + if (!originalLocation) + return false; + var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); + toDo = toDo || []; + for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { + var project_1 = _a[_i]; + addToTodo({ project: project_1, location: originalLocation }, toDo, seenProjects); + } + var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); + if (symlinkedProjectsMap) { + symlinkedProjectsMap.forEach(function (symlinkedProjects) { + for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { + var symlinkedProject = symlinkedProjects_2[_i]; + addToTodo({ project: symlinkedProject, location: originalLocation }, toDo, seenProjects); + } + }); + } + return true; + }); + return toDo; + } + function addToTodo(projectAndLocation, toDo, seenProjects) { + if (ts.addToSeen(seenProjects, projectAndLocation.project.projectName)) + toDo.push(projectAndLocation); + } + function documentSpanLocation(_a) { + var fileName = _a.fileName, textSpan = _a.textSpan; + return { fileName: fileName, position: textSpan.start }; + } + function getMappedLocation(location, projectService, project) { + var mapsTo = project.getSourceMapper().tryGetOriginalLocation(location); + return mapsTo && projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined; + } var Session = (function () { function Session(opts) { var _a; @@ -117281,6 +119354,9 @@ var ts; _a[server.CommandNames.DefinitionAndBoundSpanFull] = function (request) { return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, false)); }, + _a[server.CommandNames.EmitOutput] = function (request) { + return _this.requiredResponse(_this.getEmitOutput(request.arguments)); + }, _a[server.CommandNames.TypeDefinition] = function (request) { return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, @@ -117570,8 +119646,12 @@ var ts; var openFiles = event.data.openFiles; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case server.LargeFileReferencedEvent: + var _a = event.data, file = _a.file, fileSize = _a.fileSize, maxFileSize_1 = _a.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, "largeFileReferenced"); + break; case server.ConfigFileDiagEvent: - var _a = event.data, triggerFile = _a.triggerFile, configFile = _a.configFileName, diagnostics = _a.diagnostics; + var _b = event.data, triggerFile = _b.triggerFile, configFile = _b.configFileName, diagnostics = _b.diagnostics; var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); this.event({ triggerFile: triggerFile, @@ -117687,7 +119767,7 @@ var ts; } var _a = checkList[index], fileName = _a.fileName, project = _a.project; index++; - project.updateGraph(); + server.updateProjectIfDirty(project); if (!project.containsFile(fileName, requireOpen)) { return; } @@ -117808,33 +119888,55 @@ var ts; Session.prototype.getDefinition = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); - if (!definitions) { - return server.emptyArray; - } - if (simplifiedResult) { - return this.mapDefinitionInfo(definitions, project); - } - return definitions.map(Session.mapToOriginalLocation); + var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || server.emptyArray, project); + return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(Session.mapToOriginalLocation); + }; + Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { + var _this = this; + return definitions.map(function (info) { + var newLoc = getMappedLocation(documentSpanLocation(info), _this.projectService, project); + return !newLoc ? info : { + containerKind: info.containerKind, + containerName: info.containerName, + fileName: newLoc.fileName, + kind: info.kind, + name: info.name, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan, + }; + }); }; Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - var scriptInfo = project.getScriptInfo(file); - var definitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); - if (!definitionAndBoundSpan || !definitionAndBoundSpan.definitions) { + var scriptInfo = ts.Debug.assertDefined(project.getScriptInfo(file)); + var unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); + if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) { return { definitions: server.emptyArray, textSpan: undefined }; } + var definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project); + var textSpan = unmappedDefinitionAndBoundSpan.textSpan; if (simplifiedResult) { return { - definitions: this.mapDefinitionInfo(definitionAndBoundSpan.definitions, project), - textSpan: this.toLocationTextSpan(definitionAndBoundSpan.textSpan, scriptInfo) + definitions: this.mapDefinitionInfo(definitions, project), + textSpan: this.toLocationTextSpan(textSpan, scriptInfo) }; } - return __assign({}, definitionAndBoundSpan, { definitions: definitionAndBoundSpan.definitions.map(Session.mapToOriginalLocation) }); + return { + definitions: definitions.map(Session.mapToOriginalLocation), + textSpan: textSpan, + }; + }; + Session.prototype.getEmitOutput = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEmitOutput(file); }; Session.prototype.mapDefinitionInfo = function (definitions, project) { var _this = this; @@ -117860,20 +119962,31 @@ var ts; Session.prototype.getTypeDefinition = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); - if (!definitions) { - return server.emptyArray; - } + var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || server.emptyArray, project); return this.mapDefinitionInfo(definitions, project); }; + Session.prototype.mapImplementationLocations = function (implementations, project) { + var _this = this; + return implementations.map(function (info) { + var newLoc = getMappedLocation(documentSpanLocation(info), _this.projectService, project); + return !newLoc ? info : { + fileName: newLoc.fileName, + kind: info.kind, + displayParts: info.displayParts, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan, + }; + }); + }; Session.prototype.getImplementation = function (args, simplifiedResult) { var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - var implementations = project.getLanguageService().getImplementationAtPosition(file, position); - if (!implementations) { - return server.emptyArray; - } + var implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || server.emptyArray, project); if (simplifiedResult) { return implementations.map(function (_a) { var fileName = _a.fileName, textSpan = _a.textSpan; @@ -117967,7 +120080,7 @@ var ts; }; Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName).project; - project.updateGraph(); + server.updateProjectIfDirty(project); var projectInfo = { configFileName: project.getProjectName(), languageServiceDisabled: !project.languageServiceEnabled, @@ -117980,7 +120093,7 @@ var ts; var position = this.getPositionInFile(args, file); return project.getLanguageService().getRenameInfo(file, position); }; - Session.prototype.getProjects = function (args) { + Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { var projects; var symLinkedProjects; if (args.projectFileName) { @@ -117990,12 +120103,17 @@ var ts; } } else { - var scriptInfo = this.projectService.getScriptInfo(args.file); + var scriptInfo = getScriptInfoEnsuringProjectsUptoDate ? + this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : + this.projectService.getScriptInfo(args.file); + if (!scriptInfo) { + return ignoreNoProjectError ? server.emptyArray : server.Errors.ThrowNoProject(); + } projects = scriptInfo.containingProjects; symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); }); - if ((!projects || !projects.length) && !symLinkedProjects) { + if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { return server.Errors.ThrowNoProject(); } return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; @@ -118011,138 +120129,60 @@ var ts; return info.getDefaultProject(); }; Session.prototype.getRenameLocations = function (args, simplifiedResult) { - var _this = this; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); - if (simplifiedResult) { - var defaultProject = this.getDefaultProject(args); - var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); - if (!renameInfo) { - return undefined; - } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: server.emptyArray - }; - } - var fileSpans = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { - var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); - if (!renameLocations) { - return server.emptyArray; - } - return renameLocations.map(function (location) { - var locationScriptInfo = project.getScriptInfo(location.fileName); - return { - file: location.fileName, - start: locationScriptInfo.positionToLineOffset(location.textSpan.start), - end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)), - }; - }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = []; - for (var _i = 0, fileSpans_1 = fileSpans; _i < fileSpans_1.length; _i++) { - var cur = fileSpans_1[_i]; - var curFileAccum = void 0; - if (locs.length > 0) { - curFileAccum = locs[locs.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; - } - } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - locs.push(curFileAccum); - } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - } - return { info: renameInfo, locs: locs }; - } - else { - return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (p, file) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); - } - function renameLocationIsEqualTo(a, b) { - if (a === b) { - return true; - } - if (!a || !b) { - return false; - } - return a.fileName === b.fileName && - a.textSpan.start === b.textSpan.start && - a.textSpan.length === b.textSpan.length; - } - function compareRenameLocation(a, b) { - if (a.file < b.file) { - return -1; - } - else if (a.file > b.file) { - return 1; - } - else { - if (a.start.line < b.start.line) { - return 1; - } - else if (a.start.line > b.start.line) { - return -1; - } - else { - return b.start.offset - a.start.offset; - } - } + var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, position: position }, this.projectService, !!args.findInStrings, !!args.findInComments); + if (!simplifiedResult) + return locations; + var defaultProject = this.getDefaultProject(args); + var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + return { info: renameInfo, locs: this.toSpanGroups(locations) }; + }; + Session.mapRenameInfo = function (_a) { + var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; + return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + }; + Session.prototype.toSpanGroups = function (locations) { + var map = ts.createMap(); + for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { + var _a = locations_1[_i], fileName = _a.fileName, textSpan = _a.textSpan; + var group_1 = map.get(fileName); + if (!group_1) + map.set(fileName, group_1 = { file: fileName, locs: [] }); + group_1.locs.push(this.toLocationTextSpan(textSpan, ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); } + return ts.arrayFrom(map.values()); }; Session.prototype.getReferences = function (args, simplifiedResult) { var _this = this; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); - var defaultProject = this.getDefaultProject(args); - var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); + var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, position: position }, this.projectService); if (simplifiedResult) { + var defaultProject = this.getDefaultProject(args); + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); - var displayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : ""; + var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : ""; var nameSpan = nameInfo && nameInfo.textSpan; - var nameColStart = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; - var nameText = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; - var refs = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { - var references = project.getLanguageService().getReferencesAtPosition(file, position); - if (!references) { - return server.emptyArray; - } - return references.map(function (ref) { - var refScriptInfo = project.getScriptInfo(ref.fileName); - var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); - var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); - var lineText = refScriptInfo.getSnapshot().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; + var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; + var symbolName_1 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; + var refs = ts.flatMap(references, function (referencedSymbol) { + return referencedSymbol.references.map(function (_a) { + var fileName = _a.fileName, textSpan = _a.textSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition; + var scriptInfo = ts.Debug.assertDefined(_this.projectService.getScriptInfo(fileName)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var lineSpan = scriptInfo.lineToTextSpan(start.line - 1); + var lineText = scriptInfo.getSnapshot().getText(lineSpan.start, ts.textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); + return __assign({}, toFileSpan(fileName, textSpan, scriptInfo), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition }); }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; + }); + var result = { refs: refs, symbolName: symbolName_1, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; + return result; } else { - return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { return project.getLanguageService().findReferences(file, position); }, undefined, ts.equateValues); - } - function areReferencesResponseItemsForTheSameLocation(a, b) { - if (a && b) { - return a.file === b.file && - a.start === b.start && - a.end === b.end; - } - return false; + return references; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { @@ -118357,18 +120397,17 @@ var ts; return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file)); }); return simplifiedResult - ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(project, action); }) })); }) + ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action); }) })); }) : result; }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { var _this = this; - var info = this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file); + var projects = this.getProjects(args, true, true); + var info = this.projectService.getScriptInfo(args.file); if (!info) { return server.emptyArray; } - var projects = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; - var symLinkedProjects = !args.projectFileName && this.projectService.getSymlinkedProjects(info); - return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects, function (project, info) { + return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, projects, function (project, info) { var result; if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.isOrphan() && !project.getCompilationSettings().noEmit) { result = { @@ -118518,48 +120557,42 @@ var ts; : tree; }; Session.prototype.getNavigateToItems = function (args, simplifiedResult) { - var projects = this.getProjects(args); - var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; - if (simplifiedResult) { - return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { - if (fileName && !file) { - return undefined; - } - var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); - if (!navItems) { - return server.emptyArray; - } - return navItems.map(function (navItem) { - var scriptInfo = project.getScriptInfo(navItem.fileName); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - isCaseSensitive: navItem.isCaseSensitive, - matchKind: navItem.matchKind, - file: navItem.fileName, - start: scriptInfo.positionToLineOffset(navItem.textSpan.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)) - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); + var _this = this; + var full = this.getFullNavigateToItems(args); + return !simplifiedResult ? full : full.map(function (navItem) { + var _a = _this.getFileAndProject({ file: navItem.fileName }), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfo(file); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + isCaseSensitive: navItem.isCaseSensitive, + matchKind: navItem.matchKind, + file: navItem.fileName, + start: scriptInfo.positionToLineOffset(navItem.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)) + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }; + Session.prototype.getFullNavigateToItems = function (args) { + var currentFileOnly = args.currentFileOnly, searchValue = args.searchValue, maxResultCount = args.maxResultCount; + if (currentFileOnly) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file); } else { - return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { - if (fileName && !file) { - return undefined; - } - return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); - }, undefined, navigateToItemIsEqualTo); + return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), this.projectService, function (project) { + return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, undefined, project.isNonTsProject()); + }, documentSpanLocation, navigateToItemIsEqualTo); } function navigateToItemIsEqualTo(a, b) { if (a === b) { @@ -118579,14 +120612,6 @@ var ts; a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length; } - function areNavToItemsForTheSameLocation(a, b) { - if (a && b) { - return a.file === b.file && - a.start === b.start && - a.end === b.end; - } - return false; - } }; Session.prototype.getSupportedCodeFixes = function () { return ts.getSupportedCodeFixes(); @@ -118632,7 +120657,7 @@ var ts; var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); mappedRenameLocation = getLocationInNewDocument(ts.getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); } - return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(project, edits) }; + return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(edits) }; } else { return result; @@ -118644,7 +120669,7 @@ var ts; var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { - return this.mapTextChangesToCodeEdits(project, changes); + return this.mapTextChangesToCodeEdits(changes); } else { return changes; @@ -118656,32 +120681,16 @@ var ts; var newPath = server.toNormalizedPath(args.newFilePath); var formatOptions = this.getHostFormatOptions(); var preferences = this.getHostPreferences(); - var changes = []; - this.projectService.forEachProject(function (project) { - if (project.isOrphan() || !project.languageServiceEnabled) - return; - var _loop_8 = function (fileTextChanges) { - if (!changes.some(function (f) { return f.fileName === fileTextChanges.fileName; })) { - changes.push(simplifiedResult ? _this.mapTextChangeToCodeEdit(project, fileTextChanges) : fileTextChanges); - } - }; - for (var _i = 0, _a = project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); _i < _a.length; _i++) { - var fileTextChanges = _a[_i]; - _loop_8(fileTextChanges); - } - }); - return changes; + var changes = combineProjectOutputFromEveryProject(this.projectService, function (project) { return project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); }, function (a, b) { return a.fileName === b.fileName; }); + return simplifiedResult ? changes.map(function (c) { return _this.mapTextChangeToCodeEdit(c); }) : changes; }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { var _this = this; - if (args.errorCodes.length === 0) { - return undefined; - } var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); - return simplifiedResult ? codeActions.map(function (codeAction) { return _this.mapCodeFixAction(project, codeAction); }) : codeActions; + return simplifiedResult ? codeActions.map(function (codeAction) { return _this.mapCodeFixAction(codeAction); }) : codeActions; }; Session.prototype.getCombinedCodeFix = function (_a, simplifiedResult) { var scope = _a.scope, fixId = _a.fixId; @@ -118689,7 +120698,7 @@ var ts; var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { - return { changes: this.mapTextChangesToCodeEdits(project, res.changes), commands: res.commands }; + return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands }; } else { return res; @@ -118722,22 +120731,20 @@ var ts; } return { startPosition: startPosition, endPosition: endPosition }; }; - Session.prototype.mapCodeAction = function (project, _a) { + Session.prototype.mapCodeAction = function (_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; - return { description: description, changes: this.mapTextChangesToCodeEdits(project, changes), commands: commands }; + return { description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands }; }; - Session.prototype.mapCodeFixAction = function (project, _a) { + Session.prototype.mapCodeFixAction = function (_a) { var fixName = _a.fixName, description = _a.description, changes = _a.changes, commands = _a.commands, fixId = _a.fixId, fixAllDescription = _a.fixAllDescription; - return { fixName: fixName, description: description, changes: this.mapTextChangesToCodeEdits(project, changes), commands: commands, fixId: fixId, fixAllDescription: fixAllDescription }; + return { fixName: fixName, description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands, fixId: fixId, fixAllDescription: fixAllDescription }; }; - Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { + Session.prototype.mapTextChangesToCodeEdits = function (textChanges) { var _this = this; - return textChanges.map(function (change) { return _this.mapTextChangeToCodeEdit(project, change); }); + return textChanges.map(function (change) { return _this.mapTextChangeToCodeEdit(change); }); }; - Session.prototype.mapTextChangeToCodeEdit = function (project, change) { - var _this = this; - var path = server.normalizedPathToPath(server.toNormalizedPath(change.fileName), this.host.getCurrentDirectory(), function (fileName) { return _this.getCanonicalFileName(fileName); }); - return mapTextChangesToCodeEdits(change, project.getSourceFileOrConfigFile(path)); + Session.prototype.mapTextChangeToCodeEdit = function (change) { + return mapTextChangesToCodeEdits(change, this.projectService.getScriptInfoOrConfig(change.fileName)); }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { @@ -118900,24 +120907,23 @@ var ts; return Session; }()); server.Session = Session; - function mapTextChangesToCodeEdits(textChanges, sourceFile) { - ts.Debug.assert(!!textChanges.isNewFile === !sourceFile); - if (sourceFile) { - return { - fileName: textChanges.fileName, - textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, sourceFile); }), - }; - } - else { - return convertNewFileTextChangeToCodeEdit(textChanges); - } + function toFileSpan(fileName, textSpan, scriptInfo) { + return { file: fileName, start: scriptInfo.positionToLineOffset(textSpan.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) }; } - function convertTextChangeToCodeEdit(change, sourceFile) { - return { - start: convertToLocation(sourceFile.getLineAndCharacterOfPosition(change.span.start)), - end: convertToLocation(sourceFile.getLineAndCharacterOfPosition(change.span.start + change.span.length)), - newText: change.newText ? change.newText : "", - }; + function mapTextChangesToCodeEdits(textChanges, scriptInfo) { + ts.Debug.assert(!!textChanges.isNewFile === !scriptInfo, "Expected isNewFile for (only) new files", function () { return JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo }); }); + return scriptInfo + ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, scriptInfo); }) } + : convertNewFileTextChangeToCodeEdit(textChanges); + } + function convertTextChangeToCodeEdit(change, scriptInfo) { + return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, ts.textSpanEnd(change.span)), newText: change.newText }; + } + function positionToLineOffset(info, position) { + return server.isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position); + } + function locationFromLineAndCharacter(lc) { + return { line: lc.line + 1, offset: lc.character + 1 }; } function convertNewFileTextChangeToCodeEdit(textChanges) { ts.Debug.assert(textChanges.textChanges.length === 1); @@ -119795,7 +121801,7 @@ var ts; }); Logger.prototype.write = function (s) { if (this.fd >= 0) { - var buf = Buffer.from ? Buffer.from(s) : new Buffer(s); + var buf = sys.bufferFrom(s); // tslint:disable-next-line no-null-keyword fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null); // TODO: GH#18217 } @@ -120010,7 +122016,7 @@ var ts; break; } default: - ts.assertTypeIsNever(response); + ts.assertType(response); } }; NodeTypingsInstaller.prototype.scheduleRequest = function (request) { @@ -120392,7 +122398,7 @@ var ts; sys.watchDirectory = watchDirectorySwallowingException; } // Override sys.write because fs.writeSync is not reliable on Node 4 - sys.write = function (s) { return writeMessage(Buffer.from ? Buffer.from(s, "utf8") : new Buffer(s, "utf8")); }; + sys.write = function (s) { return writeMessage(sys.bufferFrom(s, "utf8")); }; sys.watchFile = function (fileName, callback) { var watchedFile = pollingWatchedFileSet.addFile(fileName, callback); return { diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index ad8fd411384ea..a16288c6c2725 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -13,10 +13,8 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ - - declare namespace ts { - const versionMajorMinor = "3.0"; + const versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ const version: string; } @@ -62,526 +60,6 @@ declare namespace ts { interface Push { push(...values: T[]): void; } - type EqualityComparer = (a: T, b: T) => boolean; - type Comparer = (a: T, b: T) => Comparison; - enum Comparison { - LessThan = -1, - EqualTo = 0, - GreaterThan = 1 - } -} -declare namespace ts { - /** Create a new map. If a template object is provided, the map will copy entries from it. */ - function createMap(): Map; - function createMapFromEntries(entries: [string, T][]): Map; - function createMapFromTemplate(template: MapLike): Map; - const MapCtr: new () => Map; - function length(array: ReadonlyArray | undefined): number; - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEach(array: ReadonlyArray | undefined, callback: (element: T, index: number) => U | undefined): U | undefined; - /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ - function firstDefined(array: ReadonlyArray | undefined, callback: (element: T, index: number) => U | undefined): U | undefined; - function firstDefinedIterator(iter: Iterator, callback: (element: T) => U | undefined): U | undefined; - function zipWith(arrayA: ReadonlyArray, arrayB: ReadonlyArray, callback: (a: T, b: U, index: number) => V): V[]; - function zipToIterator(arrayA: ReadonlyArray, arrayB: ReadonlyArray): Iterator<[T, U]>; - function zipToMap(keys: ReadonlyArray, values: ReadonlyArray): Map; - /** - * Iterates through `array` by index and performs the callback on each element of array until the callback - * returns a falsey value, then returns false. - * If no such value is found, the callback is applied to each element of array and `true` is returned. - */ - function every(array: ReadonlyArray, callback: (element: T, index: number) => boolean): boolean; - /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ - function find(array: ReadonlyArray, predicate: (element: T, index: number) => element is U): U | undefined; - function find(array: ReadonlyArray, predicate: (element: T, index: number) => boolean): T | undefined; - function findLast(array: ReadonlyArray, predicate: (element: T, index: number) => element is U): U | undefined; - function findLast(array: ReadonlyArray, predicate: (element: T, index: number) => boolean): T | undefined; - /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ - function findIndex(array: ReadonlyArray, predicate: (element: T, index: number) => boolean, startIndex?: number): number; - function findLastIndex(array: ReadonlyArray, predicate: (element: T, index: number) => boolean, startIndex?: number): number; - /** - * Returns the first truthy result of `callback`, or else fails. - * This is like `forEach`, but never returns undefined. - */ - function findMap(array: ReadonlyArray, callback: (element: T, index: number) => U | undefined): U; - function contains(array: ReadonlyArray | undefined, value: T, equalityComparer?: EqualityComparer): boolean; - function arraysEqual(a: ReadonlyArray, b: ReadonlyArray, equalityComparer?: EqualityComparer): boolean; - function indexOfAnyCharCode(text: string, charCodes: ReadonlyArray, start?: number): number; - function countWhere(array: ReadonlyArray, predicate: (x: T, i: number) => boolean): number; - /** - * Filters an array by a predicate function. Returns the same array instance if the predicate is - * true for all elements, otherwise returns a new array instance containing the filtered subset. - */ - function filter(array: T[], f: (x: T) => x is U): U[]; - function filter(array: T[], f: (x: T) => boolean): T[]; - function filter(array: ReadonlyArray, f: (x: T) => x is U): ReadonlyArray; - function filter(array: ReadonlyArray, f: (x: T) => boolean): ReadonlyArray; - function filter(array: T[] | undefined, f: (x: T) => x is U): U[] | undefined; - function filter(array: T[] | undefined, f: (x: T) => boolean): T[] | undefined; - function filter(array: ReadonlyArray | undefined, f: (x: T) => x is U): ReadonlyArray | undefined; - function filter(array: ReadonlyArray | undefined, f: (x: T) => boolean): ReadonlyArray | undefined; - function filterMutate(array: T[], f: (x: T, i: number, array: T[]) => boolean): void; - function clear(array: {}[]): void; - function map(array: ReadonlyArray, f: (x: T, i: number) => U): U[]; - function map(array: ReadonlyArray | undefined, f: (x: T, i: number) => U): U[] | undefined; - function mapIterator(iter: Iterator, mapFn: (x: T) => U): Iterator; - function sameMap(array: T[], f: (x: T, i: number) => T): T[]; - function sameMap(array: ReadonlyArray, f: (x: T, i: number) => T): ReadonlyArray; - function sameMap(array: T[] | undefined, f: (x: T, i: number) => T): T[] | undefined; - function sameMap(array: ReadonlyArray | undefined, f: (x: T, i: number) => T): ReadonlyArray | undefined; - /** - * Flattens an array containing a mix of array or non-array elements. - * - * @param array The array to flatten. - */ - function flatten(array: ReadonlyArray | undefined>): T[]; - function flatten(array: ReadonlyArray | undefined> | undefined): T[] | undefined; - /** - * Maps an array. If the mapped value is an array, it is spread into the result. - * - * @param array The array to map. - * @param mapfn The callback used to map the result into one or more values. - */ - function flatMap(array: ReadonlyArray, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[]; - function flatMap(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[] | undefined; - function flatMapIterator(iter: Iterator, mapfn: (x: T) => ReadonlyArray | Iterator | undefined): Iterator; - /** - * Maps an array. If the mapped value is an array, it is spread into the result. - * Avoids allocation if all elements map to themselves. - * - * @param array The array to map. - * @param mapfn The callback used to map the result into one or more values. - */ - function sameFlatMap(array: T[], mapfn: (x: T, i: number) => T | ReadonlyArray): T[]; - function sameFlatMap(array: ReadonlyArray, mapfn: (x: T, i: number) => T | ReadonlyArray): ReadonlyArray; - function mapAllOrFail(array: ReadonlyArray, mapFn: (x: T, i: number) => U | undefined): U[] | undefined; - function mapDefined(array: ReadonlyArray | undefined, mapFn: (x: T, i: number) => U | undefined): U[]; - function mapDefinedIterator(iter: Iterator, mapFn: (x: T) => U | undefined): Iterator; - const emptyIterator: Iterator; - function singleIterator(value: T): Iterator; - /** - * Maps contiguous spans of values with the same key. - * - * @param array The array to map. - * @param keyfn A callback used to select the key for an element. - * @param mapfn A callback used to map a contiguous chunk of values to a single value. - */ - function spanMap(array: ReadonlyArray, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[]; - function spanMap(array: ReadonlyArray | undefined, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] | undefined; - function mapEntries(map: ReadonlyMap, f: (key: string, value: T) => [string, U]): Map; - function mapEntries(map: ReadonlyMap | undefined, f: (key: string, value: T) => [string, U]): Map | undefined; - function some(array: ReadonlyArray | undefined): array is ReadonlyArray; - function some(array: ReadonlyArray | undefined, predicate: (value: T) => boolean): boolean; - /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ - function getRangesWhere(arr: ReadonlyArray, pred: (t: T) => boolean, cb: (start: number, afterEnd: number) => void): void; - function concatenate(array1: T[], array2: T[]): T[]; - function concatenate(array1: ReadonlyArray, array2: ReadonlyArray): ReadonlyArray; - function concatenate(array1: T[] | undefined, array2: T[] | undefined): T[]; - function concatenate(array1: ReadonlyArray | undefined, array2: ReadonlyArray | undefined): ReadonlyArray; - /** - * Deduplicates an unsorted array. - * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. - * @param comparer An optional `Comparer` used to sort entries before comparison, though the - * result will remain in the original order in `array`. - */ - function deduplicate(array: ReadonlyArray, equalityComparer?: EqualityComparer, comparer?: Comparer): T[]; - function deduplicate(array: ReadonlyArray | undefined, equalityComparer?: EqualityComparer, comparer?: Comparer): T[] | undefined; - function insertSorted(array: SortedArray, insert: T, compare: Comparer): void; - function sortAndDeduplicate(array: ReadonlyArray, comparer: Comparer, equalityComparer?: EqualityComparer): T[]; - function arrayIsEqualTo(array1: ReadonlyArray | undefined, array2: ReadonlyArray | undefined, equalityComparer?: (a: T, b: T) => boolean): boolean; - /** - * Compacts an array, removing any falsey elements. - */ - function compact(array: T[]): T[]; - function compact(array: ReadonlyArray): ReadonlyArray; - /** - * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that - * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted - * based on the provided comparer. - */ - function relativeComplement(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer: Comparer): T[] | undefined; - function sum, K extends string>(array: ReadonlyArray, prop: K): number; - /** - * Appends a value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param value The value to append to the array. If `value` is `undefined`, nothing is - * appended. - */ - function append(to: T[], value: T | undefined): T[]; - function append(to: T[] | undefined, value: T): T[]; - function append(to: T[] | undefined, value: T | undefined): T[] | undefined; - function append(to: Push, value: T | undefined): void; - /** - * Appends a range of value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - * @param start The offset in `from` at which to start copying values. - * @param end The offset in `from` at which to stop copying values (non-inclusive). - */ - function addRange(to: T[], from: ReadonlyArray | undefined, start?: number, end?: number): T[]; - function addRange(to: T[] | undefined, from: ReadonlyArray | undefined, start?: number, end?: number): T[] | undefined; - /** - * @return Whether the value was added. - */ - function pushIfUnique(array: T[], toAdd: T, equalityComparer?: EqualityComparer): boolean; - /** - * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. - */ - function appendIfUnique(array: T[] | undefined, toAdd: T, equalityComparer?: EqualityComparer): T[]; - /** - * Returns a new sorted array. - */ - function sort(array: ReadonlyArray, comparer: Comparer): T[]; - function arrayIterator(array: ReadonlyArray): Iterator; - /** - * Stable sort of an array. Elements equal to each other maintain their relative position in the array. - */ - function stableSort(array: ReadonlyArray, comparer: Comparer): T[]; - function rangeEquals(array1: ReadonlyArray, array2: ReadonlyArray, pos: number, end: number): boolean; - /** - * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. - * A negative offset indicates the element should be retrieved from the end of the array. - */ - function elementAt(array: ReadonlyArray | undefined, offset: number): T | undefined; - /** - * Returns the first element of an array if non-empty, `undefined` otherwise. - */ - function firstOrUndefined(array: ReadonlyArray): T | undefined; - function first(array: ReadonlyArray): T; - /** - * Returns the last element of an array if non-empty, `undefined` otherwise. - */ - function lastOrUndefined(array: ReadonlyArray): T | undefined; - function last(array: ReadonlyArray): T; - /** - * Returns the only element of an array if it contains only one element, `undefined` otherwise. - */ - function singleOrUndefined(array: ReadonlyArray | undefined): T | undefined; - /** - * Returns the only element of an array if it contains only one element; otheriwse, returns the - * array. - */ - function singleOrMany(array: T[]): T | T[]; - function singleOrMany(array: ReadonlyArray): T | ReadonlyArray; - function singleOrMany(array: T[] | undefined): T | T[] | undefined; - function singleOrMany(array: ReadonlyArray | undefined): T | ReadonlyArray | undefined; - function replaceElement(array: ReadonlyArray, index: number, value: T): T[]; - /** - * Performs a binary search, finding the index at which `value` occurs in `array`. - * If no such index is found, returns the 2's-complement of first index at which - * `array[index]` exceeds `value`. - * @param array A sorted array whose first element must be no larger than number - * @param value The value to be searched for in the array. - * @param keySelector A callback used to select the search key from `value` and each element of - * `array`. - * @param keyComparer A callback used to compare two keys in a sorted array. - * @param offset An offset into `array` at which to start the search. - */ - function binarySearch(array: ReadonlyArray, value: T, keySelector: (v: T) => U, keyComparer: Comparer, offset?: number): number; - function reduceLeft(array: ReadonlyArray | undefined, f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; - function reduceLeft(array: ReadonlyArray, f: (memo: T, value: T, i: number) => T): T | undefined; - /** - * Indicates whether a map-like contains an own property with the specified key. - * - * @param map A map-like. - * @param key A property key. - */ - function hasProperty(map: MapLike, key: string): boolean; - /** - * Gets the value of an owned property in a map-like. - * - * @param map A map-like. - * @param key A property key. - */ - function getProperty(map: MapLike, key: string): T | undefined; - /** - * Gets the owned, enumerable property keys of a map-like. - */ - function getOwnKeys(map: MapLike): string[]; - function getOwnValues(sparseArray: T[]): T[]; - /** Shims `Array.from`. */ - function arrayFrom(iterator: Iterator, map: (t: T) => U): U[]; - function arrayFrom(iterator: Iterator): T[]; - function assign(t: T, ...args: (T | undefined)[]): T; - /** - * Performs a shallow equality comparison of the contents of two map-likes. - * - * @param left A map-like whose properties should be compared. - * @param right A map-like whose properties should be compared. - */ - function equalOwnProperties(left: MapLike | undefined, right: MapLike | undefined, equalityComparer?: EqualityComparer): boolean; - /** - * Creates a map from the elements of an array. - * - * @param array the array of input elements. - * @param makeKey a function that produces a key for a given element. - * - * This function makes no effort to avoid collisions; if any two elements produce - * the same key with the given 'makeKey' function, then the element with the higher - * index in the array will be the one associated with the produced key. - */ - function arrayToMap(array: ReadonlyArray, makeKey: (value: T) => string | undefined): Map; - function arrayToMap(array: ReadonlyArray, makeKey: (value: T) => string | undefined, makeValue: (value: T) => U): Map; - function arrayToNumericMap(array: ReadonlyArray, makeKey: (value: T) => number): T[]; - function arrayToNumericMap(array: ReadonlyArray, makeKey: (value: T) => number, makeValue: (value: T) => U): U[]; - function arrayToMultiMap(values: ReadonlyArray, makeKey: (value: T) => string): MultiMap; - function arrayToMultiMap(values: ReadonlyArray, makeKey: (value: T) => string, makeValue: (value: T) => U): MultiMap; - function group(values: ReadonlyArray, getGroupId: (value: T) => string): ReadonlyArray>; - function clone(object: T): T; - function extend(first: T1, second: T2): T1 & T2; - interface MultiMap extends Map { - /** - * Adds the value to an array of values associated with the key, and returns the array. - * Creates the array if it does not already exist. - */ - add(key: string, value: T): T[]; - /** - * Removes a value from an array of values associated with the key. - * Does not preserve the order of those values. - * Does nothing if `key` is not in `map`, or `value` is not in `map[key]`. - */ - remove(key: string, value: T): void; - } - function createMultiMap(): MultiMap; - /** - * Tests whether a value is an array. - */ - function isArray(value: any): value is ReadonlyArray<{}>; - function toArray(value: T | T[]): T[]; - function toArray(value: T | ReadonlyArray): ReadonlyArray; - /** - * Tests whether a value is string - */ - function isString(text: any): text is string; - function tryCast(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut | undefined; - function tryCast(value: T, test: (value: T) => boolean): T | undefined; - function cast(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut; - /** Does nothing. */ - function noop(_?: {} | null | undefined): void; - /** Do nothing and return false */ - function returnFalse(): false; - /** Do nothing and return true */ - function returnTrue(): true; - /** Returns its argument. */ - function identity(x: T): T; - /** Returns lower case string */ - function toLowerCase(x: string): string; - /** Throws an error because a function is not implemented. */ - function notImplemented(): never; - function memoize(callback: () => T): () => T; - /** - * High-order function, creates a function that executes a function composition. - * For example, `chain(a, b)` is the equivalent of `x => ((a', b') => y => b'(a'(y)))(a(x), b(x))` - * - * @param args The functions to chain. - */ - function chain(...args: ((t: T) => (u: U) => U)[]): (t: T) => (u: U) => U; - /** - * High-order function, composes functions. Note that functions are composed inside-out; - * for example, `compose(a, b)` is the equivalent of `x => b(a(x))`. - * - * @param args The functions to compose. - */ - function compose(...args: ((t: T) => T)[]): (t: T) => T; - enum AssertionLevel { - None = 0, - Normal = 1, - Aggressive = 2, - VeryAggressive = 3 - } - /** - * Safer version of `Function` which should not be called. - * Every function should be assignable to this, but this should not be assignable to every function. - */ - type AnyFunction = (...args: never[]) => void; - namespace Debug { - let currentAssertionLevel: AssertionLevel; - let isDebugging: boolean; - function shouldAssert(level: AssertionLevel): boolean; - function assert(expression: boolean, message?: string, verboseDebugInfo?: string | (() => string), stackCrawlMark?: AnyFunction): void; - function assertEqual(a: T, b: T, msg?: string, msg2?: string): void; - function assertLessThan(a: number, b: number, msg?: string): void; - function assertLessThanOrEqual(a: number, b: number): void; - function assertGreaterThanOrEqual(a: number, b: number): void; - function fail(message?: string, stackCrawlMark?: AnyFunction): never; - function assertDefined(value: T | null | undefined, message?: string): T; - function assertEachDefined>(value: A, message?: string): A; - function assertNever(member: never, message?: string, stackCrawlMark?: AnyFunction): never; - function getFunctionName(func: AnyFunction): any; - } - function equateValues(a: T, b: T): boolean; - /** - * Compare the equality of two strings using a case-sensitive ordinal comparison. - * - * Case-sensitive comparisons compare both strings one code-point at a time using the integer - * value of each code-point after applying `toUpperCase` to each string. We always map both - * strings to their upper-case form as some unicode characters do not properly round-trip to - * lowercase (such as `ẞ` (German sharp capital s)). - */ - function equateStringsCaseInsensitive(a: string, b: string): boolean; - /** - * Compare the equality of two strings using a case-sensitive ordinal comparison. - * - * Case-sensitive comparisons compare both strings one code-point at a time using the - * integer value of each code-point. - */ - function equateStringsCaseSensitive(a: string, b: string): boolean; - /** - * Compare two numeric values for their order relative to each other. - * To compare strings, use any of the `compareStrings` functions. - */ - function compareValues(a: number | undefined, b: number | undefined): Comparison; - function min(a: T, b: T, compare: Comparer): T; - /** - * Compare two strings using a case-insensitive ordinal comparison. - * - * Ordinal comparisons are based on the difference between the unicode code points of both - * strings. Characters with multiple unicode representations are considered unequal. Ordinal - * comparisons provide predictable ordering, but place "a" after "B". - * - * Case-insensitive comparisons compare both strings one code-point at a time using the integer - * value of each code-point after applying `toUpperCase` to each string. We always map both - * strings to their upper-case form as some unicode characters do not properly round-trip to - * lowercase (such as `ẞ` (German sharp capital s)). - */ - function compareStringsCaseInsensitive(a: string, b: string): Comparison; - /** - * Compare two strings using a case-sensitive ordinal comparison. - * - * Ordinal comparisons are based on the difference between the unicode code points of both - * strings. Characters with multiple unicode representations are considered unequal. Ordinal - * comparisons provide predictable ordering, but place "a" after "B". - * - * Case-sensitive comparisons compare both strings one code-point at a time using the integer - * value of each code-point. - */ - function compareStringsCaseSensitive(a: string | undefined, b: string | undefined): Comparison; - function getStringComparer(ignoreCase?: boolean): typeof compareStringsCaseInsensitive; - function getUILocale(): string | undefined; - function setUILocale(value: string | undefined): void; - /** - * Compare two strings in a using the case-sensitive sort behavior of the UI locale. - * - * Ordering is not predictable between different host locales, but is best for displaying - * ordered data for UI presentation. Characters with multiple unicode representations may - * be considered equal. - * - * Case-sensitive comparisons compare strings that differ in base characters, or - * accents/diacritic marks, or case as unequal. - */ - function compareStringsCaseSensitiveUI(a: string, b: string): Comparison; - function compareProperties(a: T | undefined, b: T | undefined, key: K, comparer: Comparer): Comparison; - /** True is greater than false. */ - function compareBooleans(a: boolean, b: boolean): Comparison; - /** - * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough. - * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance. - * - * If there is a candidate that's the same except for case, return that. - * If there is a candidate that's within one edit of the name, return that. - * Otherwise, return the candidate with the smallest Levenshtein distance, - * except for candidates: - * * With no name - * * Whose length differs from the target name by more than 0.34 of the length of the name. - * * Whose levenshtein distance is more than 0.4 of the length of the name - * (0.4 allows 1 substitution/transposition for every 5 characters, - * and 1 insertion/deletion at 3 characters) - */ - function getSpellingSuggestion(name: string, candidates: T[], getName: (candidate: T) => string | undefined): T | undefined; - function endsWith(str: string, suffix: string): boolean; - function removeSuffix(str: string, suffix: string): string; - function tryRemoveSuffix(str: string, suffix: string): string | undefined; - function stringContains(str: string, substring: string): boolean; - function fileExtensionIs(path: string, extension: string): boolean; - function fileExtensionIsOneOf(path: string, extensions: ReadonlyArray): boolean; - /** - * Takes a string like "jquery-min.4.2.3" and returns "jquery" - */ - function removeMinAndVersionNumbers(fileName: string): string; - /** Remove an item from an array, moving everything to its right one space left. */ - function orderedRemoveItem(array: T[], item: T): boolean; - /** Remove an item by index from an array, moving everything to its right one space left. */ - function orderedRemoveItemAt(array: T[], index: number): void; - function unorderedRemoveItemAt(array: T[], index: number): void; - /** Remove the *first* occurrence of `item` from the array. */ - function unorderedRemoveItem(array: T[], item: T): boolean; - type GetCanonicalFileName = (fileName: string) => string; - function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): GetCanonicalFileName; - /** Represents a "prefix*suffix" pattern. */ - interface Pattern { - prefix: string; - suffix: string; - } - function patternText({ prefix, suffix }: Pattern): string; - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern: Pattern, candidate: string): string; - /** Return the object corresponding to the best pattern to match `candidate`. */ - function findBestPatternMatch(values: ReadonlyArray, getPattern: (value: T) => Pattern, candidate: string): T | undefined; - function startsWith(str: string, prefix: string): boolean; - function removePrefix(str: string, prefix: string): string; - function tryRemovePrefix(str: string, prefix: string, getCanonicalFileName?: GetCanonicalFileName): string | undefined; - function and(f: (arg: T) => boolean, g: (arg: T) => boolean): (arg: T) => boolean; - function or(f: (arg: T) => boolean, g: (arg: T) => boolean): (arg: T) => boolean; - function assertTypeIsNever(_: never): void; - function singleElementArray(t: T | undefined): T[] | undefined; - function enumerateInsertsAndDeletes(newItems: ReadonlyArray, oldItems: ReadonlyArray, comparer: (a: T, b: U) => Comparison, inserted: (newItem: T) => void, deleted: (oldItem: U) => void, unchanged?: (oldItem: U, newItem: T) => void): void; -} -declare namespace ts { - /** Gets a timestamp with (at least) ms resolution */ - const timestamp: () => number; -} -/** Performance measurements for the compiler. */ -declare namespace ts.performance { - /** - * Marks a performance event. - * - * @param markName The name of the mark. - */ - function mark(markName: string): void; - /** - * Adds a performance measurement with the specified name. - * - * @param measureName The name of the performance measurement. - * @param startMarkName The name of the starting mark. If not supplied, the point at which the - * profiler was enabled is used. - * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is - * used. - */ - function measure(measureName: string, startMarkName?: string, endMarkName?: string): void; - /** - * Gets the number of times a marker was encountered. - * - * @param markName The name of the mark. - */ - function getCount(markName: string): number; - /** - * Gets the total duration of all measurements with the supplied name. - * - * @param measureName The name of the measure whose durations should be accumulated. - */ - function getDuration(measureName: string): number; - /** - * Iterate over each measure, performing some action - * - * @param cb The action to perform for each measure - */ - function forEachMeasure(cb: (measureName: string, duration: number) => void): void; - /** Enables (and resets) performance measurements for the compiler. */ - function enable(): void; - /** Disables performance measurements for the compiler. */ - function disable(): void; } declare namespace ts { type Path = string & { @@ -890,20 +368,21 @@ declare namespace ts { JSDocAugmentsTag = 293, JSDocClassTag = 294, JSDocCallbackTag = 295, - JSDocParameterTag = 296, - JSDocReturnTag = 297, - JSDocThisTag = 298, - JSDocTypeTag = 299, - JSDocTemplateTag = 300, - JSDocTypedefTag = 301, - JSDocPropertyTag = 302, - SyntaxList = 303, - NotEmittedStatement = 304, - PartiallyEmittedExpression = 305, - CommaListExpression = 306, - MergeDeclarationMarker = 307, - EndOfDeclarationMarker = 308, - Count = 309, + JSDocEnumTag = 296, + JSDocParameterTag = 297, + JSDocReturnTag = 298, + JSDocThisTag = 299, + JSDocTypeTag = 300, + JSDocTemplateTag = 301, + JSDocTypedefTag = 302, + JSDocPropertyTag = 303, + SyntaxList = 304, + NotEmittedStatement = 305, + PartiallyEmittedExpression = 306, + CommaListExpression = 307, + MergeDeclarationMarker = 308, + EndOfDeclarationMarker = 309, + Count = 310, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -930,11 +409,9 @@ declare namespace ts { LastBinaryOperator = 70, FirstNode = 146, FirstJSDocNode = 281, - LastJSDocNode = 302, + LastJSDocNode = 303, FirstJSDocTagNode = 292, - LastJSDocTagNode = 302, - FirstContextualKeyword = 117, - LastContextualKeyword = 145 + LastJSDocTagNode = 303 } enum NodeFlags { None = 0, @@ -957,18 +434,13 @@ declare namespace ts { JavaScriptFile = 65536, ThisNodeOrAnySubNodesHasError = 131072, HasAggregatedChildData = 262144, - PossiblyContainsDynamicImport = 524288, - PossiblyContainsImportMeta = 1048576, JSDoc = 2097152, - Ambient = 4194304, - InWithStatement = 8388608, JsonFile = 16777216, BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, ContextFlags = 12679168, - TypeExcludesFlags = 20480, - PermanentlySetIncrementalFlags = 1572864 + TypeExcludesFlags = 20480 } enum ModifierFlags { None = 0, @@ -999,42 +471,21 @@ declare namespace ts { IntrinsicIndexedElement = 2, IntrinsicElement = 3 } - enum RelationComparisonResult { - Succeeded = 1, - Failed = 2, - FailedAndReported = 3 - } interface Node extends TextRange { kind: SyntaxKind; flags: NodeFlags; - modifierFlagsCache?: ModifierFlags; - transformFlags: TransformFlags; decorators?: NodeArray; modifiers?: ModifiersArray; - id?: number; parent: Node; - original?: Node; - symbol: Symbol; - locals?: SymbolTable; - nextContainer?: Node; - localSymbol?: Symbol; - flowNode?: FlowNode; - emitNode?: EmitNode; - contextualType?: Type; - contextualMapper?: TypeMapper; } interface JSDocContainer { - jsDoc?: JSDoc[]; - jsDocCache?: ReadonlyArray; } - 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; + 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 | ExportDeclaration | EndOfFileToken; type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; - type MutableNodeArray = NodeArray & T[]; interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; - transformFlags: TransformFlags; } interface Token extends Node { kind: TKind; @@ -1054,17 +505,6 @@ declare namespace ts { type MinusToken = Token; type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; type ModifiersArray = NodeArray; - enum GeneratedIdentifierFlags { - None = 0, - Auto = 1, - Loop = 2, - Unique = 3, - Node = 4, - KindMask = 7, - ReservedInNestedScopes = 8, - Optimistic = 16, - FileLevel = 32 - } interface Identifier extends PrimaryExpression, Declaration { kind: SyntaxKind.Identifier; /** @@ -1073,23 +513,15 @@ declare namespace ts { */ escapedText: __String; originalKeywordKind?: SyntaxKind; - autoGenerateFlags?: GeneratedIdentifierFlags; - autoGenerateId?: number; isInJSDocNamespace?: boolean; - typeArguments?: NodeArray; - jsdocDotPos?: number; } interface TransientIdentifier extends Identifier { resolvedSymbol: Symbol; } - interface GeneratedIdentifier extends Identifier { - autoGenerateFlags: GeneratedIdentifierFlags; - } interface QualifiedName extends Node { kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; - jsdocDotPos?: number; } type EntityName = Identifier | QualifiedName; type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; @@ -1100,12 +532,6 @@ declare namespace ts { interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DynamicNamedDeclaration extends NamedDeclaration { - name: ComputedPropertyName; - } - interface LateBoundDeclaration extends DynamicNamedDeclaration { - name: LateBoundName; - } interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } @@ -1113,9 +539,6 @@ declare namespace ts { kind: SyntaxKind.ComputedPropertyName; expression: Expression; } - interface LateBoundName extends ComputedPropertyName { - expression: EntityNameExpression; - } interface Decorator extends Node { kind: SyntaxKind.Decorator; parent: NamedDeclaration; @@ -1123,8 +546,9 @@ declare namespace ts { } interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; - parent: DeclarationWithTypeParameters | InferTypeNode; + parent: DeclarationWithTypeParameterChildren | InferTypeNode; name: Identifier; + /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ constraint?: TypeNode; default?: TypeNode; expression?: Expression; @@ -1135,7 +559,6 @@ declare namespace ts { typeParameters?: NodeArray; parameters: NodeArray; type?: TypeNode; - typeArguments?: NodeArray; } type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { @@ -1175,7 +598,6 @@ declare namespace ts { name: BindingName; initializer?: Expression; } - type BindingElementGrandparent = BindingElement["parent"]["parent"]; interface PropertySignature extends TypeElement, JSDocContainer { kind: SyntaxKind.PropertySignature; name: PropertyName; @@ -1196,6 +618,7 @@ declare namespace ts { _objectLiteralBrandBrand: any; name?: PropertyName; } + /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { parent: ObjectLiteralExpression; @@ -1270,7 +693,6 @@ declare namespace ts { kind: SyntaxKind.Constructor; parent: ClassLikeDeclaration; body?: FunctionBody; - returnFlowNode?: FlowNode; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { @@ -1306,11 +728,6 @@ declare namespace ts { argument: TypeNode; qualifier?: EntityName; } - type LiteralImportTypeNode = ImportTypeNode & { - argument: LiteralTypeNode & { - literal: StringLiteral; - }; - }; interface ThisTypeNode extends TypeNode { kind: SyntaxKind.ThisType; } @@ -1335,7 +752,7 @@ declare namespace ts { } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; - parent: SignatureDeclaration; + parent: SignatureDeclaration | JSDocTypeExpression; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -1392,9 +809,6 @@ declare namespace ts { operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword; type: TypeNode; } - interface UniqueTypeOperatorNode extends TypeOperatorNode { - operator: SyntaxKind.UniqueKeyword; - } interface IndexedAccessTypeNode extends TypeNode { kind: SyntaxKind.IndexedAccessType; objectType: TypeNode; @@ -1413,9 +827,6 @@ declare namespace ts { } interface StringLiteral extends LiteralExpression { kind: SyntaxKind.StringLiteral; - textSourceNode?: Identifier | StringLiteralLike | NumericLiteral; - /** Note: this is only set when synthesizing a node, not during parsing. */ - singleQuote?: boolean; } type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral; interface Expression extends Node { @@ -1578,24 +989,8 @@ declare namespace ts { interface NoSubstitutionTemplateLiteral extends LiteralExpression { kind: SyntaxKind.NoSubstitutionTemplateLiteral; } - enum TokenFlags { - None = 0, - PrecedingLineBreak = 1, - PrecedingJSDocComment = 2, - Unterminated = 4, - ExtendedUnicodeEscape = 8, - Scientific = 16, - Octal = 32, - HexSpecifier = 64, - BinarySpecifier = 128, - OctalSpecifier = 256, - ContainsSeparator = 512, - BinaryOrOctalSpecifier = 384, - NumericLiteralFlags = 1008 - } interface NumericLiteral extends LiteralExpression { kind: SyntaxKind.NumericLiteral; - numericLiteralFlags: TokenFlags; } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; @@ -1628,7 +1023,6 @@ declare namespace ts { interface ArrayLiteralExpression extends PrimaryExpression { kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; - multiLine?: boolean; } interface SpreadElement extends Expression { kind: SyntaxKind.SpreadElement; @@ -1646,7 +1040,6 @@ declare namespace ts { } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { kind: SyntaxKind.ObjectLiteralExpression; - multiLine?: boolean; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; @@ -1798,12 +1191,6 @@ declare namespace ts { interface NotEmittedStatement extends Statement { kind: SyntaxKind.NotEmittedStatement; } - /** - * Marks the end of transformed declaration to properly emit exports. - */ - interface EndOfDeclarationMarker extends Statement { - kind: SyntaxKind.EndOfDeclarationMarker; - } /** * A list of comma-separated expressions. This node is only created by transformations. */ @@ -1811,12 +1198,6 @@ declare namespace ts { kind: SyntaxKind.CommaListExpression; elements: NodeArray; } - /** - * Marks the beginning of a merged transformed declaration. - */ - interface MergeDeclarationMarker extends Statement { - kind: SyntaxKind.MergeDeclarationMarker; - } interface EmptyStatement extends Statement { kind: SyntaxKind.EmptyStatement; } @@ -1831,7 +1212,6 @@ declare namespace ts { interface Block extends Statement { kind: SyntaxKind.Block; statements: NodeArray; - multiLine?: boolean; } interface VariableStatement extends Statement, JSDocContainer { kind: SyntaxKind.VariableStatement; @@ -1841,9 +1221,6 @@ declare namespace ts { kind: SyntaxKind.ExpressionStatement; expression: Expression; } - interface PrologueDirective extends ExpressionStatement { - expression: StringLiteral; - } interface IfStatement extends Statement { kind: SyntaxKind.IfStatement; expression: Expression; @@ -1943,7 +1320,8 @@ declare namespace ts { block: Block; } type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; + type DeclarationWithTypeParameters = DeclarationWithTypeParameterChildren | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; + type DeclarationWithTypeParameterChildren = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; @@ -2001,9 +1379,6 @@ declare namespace ts { } type ModuleName = Identifier | StringLiteral; type ModuleBody = NamespaceBody | JSDocNamespaceBody; - interface AmbientModuleDeclaration extends ModuleDeclaration { - body?: ModuleBlock; - } interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ModuleDeclaration; parent: ModuleBody | SourceFile; @@ -2065,7 +1440,7 @@ declare namespace ts { kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; } - interface ExportDeclaration extends DeclarationStatement { + interface ExportDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ExportDeclaration; parent: SourceFile | ModuleBlock; /** Will not be assigned in the case of `export * from "foo";` */ @@ -2184,12 +1559,17 @@ declare namespace ts { interface JSDocClassTag extends JSDocTag { kind: SyntaxKind.JSDocClassTag; } + interface JSDocEnumTag extends JSDocTag { + kind: SyntaxKind.JSDocEnumTag; + typeExpression?: JSDocTypeExpression; + } interface JSDocThisTag extends JSDocTag { kind: SyntaxKind.JSDocThisTag; typeExpression?: JSDocTypeExpression; } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; + constraint: TypeNode | undefined; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { @@ -2305,36 +1685,12 @@ declare namespace ts { path: string; name?: string; } - /** - * Subset of properties from SourceFile that are used in multiple utility functions - */ - interface SourceFileLike { - readonly text: string; - lineMap?: ReadonlyArray; - } - interface RedirectInfo { - /** Source file this redirects to. */ - readonly redirectTarget: SourceFile; - /** - * Source file for the duplicate package. This will not be used by the Program, - * but we need to keep this around so we can watch for changes in underlying. - */ - readonly unredirected: SourceFile; - } interface SourceFile extends Declaration { kind: SyntaxKind.SourceFile; statements: NodeArray; endOfFileToken: Token; fileName: string; - path: Path; text: string; - resolvedPath: Path; - /** - * If two source files are for the same version of the same package, one will redirect to the other. - * (See `createRedirectSourceFile` in program.ts.) - * The redirect will have this set. The redirected-to source file will be in `redirectTargetsSet`. - */ - redirectInfo?: RedirectInfo; amdDependencies: ReadonlyArray; moduleName?: string; referencedFiles: ReadonlyArray; @@ -2342,7 +1698,6 @@ declare namespace ts { libReferenceDirectives: ReadonlyArray; languageVariant: LanguageVariant; isDeclarationFile: boolean; - renamedDependencies?: ReadonlyMap; /** * lib.d.ts should have a reference comment like * @@ -2353,49 +1708,11 @@ declare namespace ts { */ hasNoDefaultLib: boolean; languageVersion: ScriptTarget; - scriptKind: ScriptKind; - /** - * The first "most obvious" node that makes a file an external module. - * This is intended to be the first top-level import/export, - * but could be arbitrarily nested (e.g. `import.meta`). - */ - externalModuleIndicator?: Node; - commonJsModuleIndicator?: Node; - identifiers: Map; - nodeCount: number; - identifierCount: number; - symbolCount: number; - parseDiagnostics: DiagnosticWithLocation[]; - bindDiagnostics: DiagnosticWithLocation[]; - bindSuggestionDiagnostics?: DiagnosticWithLocation[]; - jsDocDiagnostics?: DiagnosticWithLocation[]; - additionalSyntacticDiagnostics?: ReadonlyArray; - lineMap: ReadonlyArray; - classifiableNames?: ReadonlyUnderscoreEscapedMap; - resolvedModules?: Map; - resolvedTypeReferenceDirectiveNames: Map; - imports: ReadonlyArray; - /** - * When a file's references are redirected due to project reference directives, - * the original names of the references are stored in this array - */ - redirectedReferences?: ReadonlyArray; - moduleAugmentations: ReadonlyArray; - patternAmbientModules?: PatternAmbientModule[]; - ambientModuleNames: ReadonlyArray; - checkJsDirective?: CheckJsDirective; - version: string; - pragmas: PragmaMap; - localJsxNamespace?: __String; - localJsxFactory?: EntityName; } interface Bundle extends Node { kind: SyntaxKind.Bundle; prepends: ReadonlyArray; sourceFiles: ReadonlyArray; - syntheticFileReferences?: ReadonlyArray; - syntheticTypeReferences?: ReadonlyArray; - hasNoDefaultLib?: boolean; } interface InputFiles extends Node { kind: SyntaxKind.InputFiles; @@ -2467,11 +1784,6 @@ declare namespace ts { * Get a list of files in the program */ getSourceFiles(): ReadonlyArray; - /** - * Get a list of file names that were passed to 'createProgram' or referenced in a - * program source file but could not be located. - */ - getMissingFilePaths(): 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. @@ -2490,44 +1802,18 @@ declare namespace ts { getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; - getSuggestionDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. */ getTypeChecker(): TypeChecker; - getCommonSourceDirectory(): string; - getDiagnosticsProducingTypeChecker(): TypeChecker; - dropDiagnosticsProducingTypeChecker(): void; - getClassifiableNames(): UnderscoreEscapedMap; - getNodeCount(): number; - getIdentifierCount(): number; - getSymbolCount(): number; - getTypeCount(): number; - getFileProcessingDiagnostics(): DiagnosticCollection; - getResolvedTypeReferenceDirectives(): Map; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - structureIsReused?: StructureIsReused; - getSourceFileFromReference(referencingFile: SourceFile, ref: FileReference): SourceFile | undefined; - getLibFileFromReference(ref: FileReference): SourceFile | undefined; - /** Given a source file, get the name of the package it was imported from. */ - sourceFileToPackageName: Map; - /** Set of all source files that some other source file redirects to. */ - redirectTargetsSet: Map; - /** Is the file emitted file */ - isEmittedFile(file: string): boolean; - getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; } - enum StructureIsReused { - Not = 0, - SafeModules = 1, - Completely = 2 - } interface CustomTransformers { /** Custom transformers to evaluate before built-in .js transformations. */ before?: TransformerFactory[]; @@ -2572,20 +1858,12 @@ declare namespace ts { /** Contains declaration emit diagnostics */ diagnostics: ReadonlyArray; emittedFiles?: string[]; - sourceMaps?: SourceMapData[]; - } - interface TypeCheckerHost { - getCompilerOptions(): CompilerOptions; - getSourceFiles(): ReadonlyArray; - getSourceFile(fileName: string): SourceFile | undefined; - getResolvedTypeReferenceDirectives(): ReadonlyMap; } interface TypeChecker { getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; getDeclaredTypeOfSymbol(symbol: Symbol): Type; getPropertiesOfType(type: Type): Symbol[]; getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; - getTypeOfPropertyOfType(type: Type, propertyName: string): Type | undefined; getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray; getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; @@ -2593,16 +1871,10 @@ declare namespace ts { getBaseTypeOfLiteralType(type: Type): Type; getWidenedType(type: Type): Type; getReturnTypeOfSignature(signature: Signature): Type; - /** - * Gets the type of a parameter at a given position in a signature. - * Returns `any` if the index is not valid. - */ - getParameterType(signature: Signature, parameterIndex: number): Type; getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; /** Note that the resulting nodes cannot be checked. */ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; @@ -2638,23 +1910,16 @@ declare namespace ts { */ getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; - getTypeAtLocation(node: Node): Type | undefined; + getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - writeSignature(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind, writer?: EmitTextWriter): string; - writeType(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags, writer?: EmitTextWriter): string; - writeSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags, writer?: EmitTextWriter): string; - writeTypePredicate(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags, writer?: EmitTextWriter): string; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; - getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined; - getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute): Type | undefined; - isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike): boolean; /** * returns unknownSignature in the case of an error. * returns undefined if the node is not valid. @@ -2666,96 +1931,19 @@ declare namespace ts { isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; - getMergedSymbol(symbol: Symbol): Symbol; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; - /** Exclude accesses to private properties or methods with a `this` parameter that `type` doesn't satisfy. */ - isValidPropertyAccessForCompletions(node: PropertyAccessExpression | ImportTypeNode, type: Type, property: Symbol): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; - /** Follow a *single* alias to get the immediately aliased symbol. */ - getImmediateAliasedSymbol(symbol: Symbol): Symbol | undefined; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - /** Unlike `getExportsOfModule`, this includes properties of an `export =` value. */ - getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[]; getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; - /** - * Unlike `tryGetMemberInModuleExports`, this includes properties of an `export =` value. - * Does *not* return properties of primitive types. - */ - tryGetMemberInModuleExportsAndProperties(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; - getSuggestionForNonexistentProperty(name: Identifier | string, containingType: Type): string | undefined; - getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; - getSuggestionForNonexistentModule(node: Identifier, target: Symbol): string | undefined; getBaseConstraintOfType(type: Type): Type | undefined; getDefaultFromTypeParameter(type: Type): Type | undefined; - getAnyType(): Type; - getStringType(): Type; - getNumberType(): Type; - getBooleanType(): Type; - getFalseType(): Type; - getTrueType(): Type; - getVoidType(): Type; - getUndefinedType(): Type; - getNullType(): Type; - getESSymbolType(): Type; - getNeverType(): Type; - getUnionType(types: Type[], subtypeReduction?: UnionReduction): Type; - createArrayType(elementType: Type): Type; - createPromiseType(type: Type): Type; - createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): Type; - createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[] | undefined, thisParameter: Symbol | undefined, parameters: Symbol[], resolvedReturnType: Type, typePredicate: TypePredicate | undefined, minArgumentCount: number, hasRestParameter: boolean, hasLiteralTypes: boolean): Signature; - createSymbol(flags: SymbolFlags, name: __String): TransientSymbol; - createIndexInfo(type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo; - isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; - tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol | undefined; - getSymbolWalker(accept?: (symbol: Symbol) => boolean): SymbolWalker; - getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getGlobalDiagnostics(): Diagnostic[]; - getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken): EmitResolver; - getNodeCount(): number; - getIdentifierCount(): number; - getSymbolCount(): number; - getTypeCount(): number; - isArrayLikeType(type: Type): boolean; - /** - * True if `contextualType` should not be considered for completions because - * e.g. it specifies `kind: "a"` and obj has `kind: "b"`. - */ - isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean; - /** - * For a union, will include a property if it's defined in *any* of the member types. - * So for `{ a } | { b }`, this will include both `a` and `b`. - * Does not include properties of primitive types. - */ - getAllPossiblePropertiesOfTypes(type: ReadonlyArray): Symbol[]; - resolveName(name: string, location: Node, meaning: SymbolFlags, excludeGlobals: boolean): Symbol | undefined; - getJsxNamespace(location?: Node): string; - /** - * Note that this will return undefined in the following case: - * // a.ts - * export namespace N { export class C { } } - * // b.ts - * <> - * Where `C` is the symbol we're looking for. - * This should be called in a loop climbing parents of the symbol, so we'll get `N`. - */ - getAccessibleSymbolChain(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, useOnlyExternalAliasing: boolean): Symbol[] | undefined; - getTypePredicateOfSignature(signature: Signature): TypePredicate; - resolveExternalModuleSymbol(symbol: Symbol): Symbol; - /** @param node A location where we might consider accessing `this`. Not necessarily a ThisExpression. */ - tryGetThisTypeAt(node: Node): Type | undefined; - getTypeArgumentConstraint(node: TypeNode): Type | undefined; - /** - * Does *not* get *all* suggestion diagnostics, just the ones that were convenient to report in the checker. - * Others are added in computeSuggestionDiagnostics. - */ - getSuggestionDiagnostics(file: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; /** * Depending on the operation performed, it may be appropriate to throw away the checker * if the cancellation token is triggered. Typically, if it is used for error checking @@ -2763,11 +1951,6 @@ declare namespace ts { */ runWithCancellationToken(token: CancellationToken, cb: (checker: TypeChecker) => T): T; } - enum UnionReduction { - None = 0, - Literal = 1, - Subtype = 2 - } enum NodeBuilderFlags { None = 0, NoTruncation = 1, @@ -2828,41 +2011,6 @@ declare namespace ts { AllowAnyNodeKind = 4, UseAliasDefinedOutsideCurrentScope = 8 } - interface SymbolWalker { - /** Note: Return values are not ordered. */ - walkType(root: Type): { - visitedTypes: ReadonlyArray; - visitedSymbols: ReadonlyArray; - }; - /** Note: Return values are not ordered. */ - walkSymbol(root: Symbol): { - visitedTypes: ReadonlyArray; - visitedSymbols: ReadonlyArray; - }; - } - interface SymbolWriter extends SymbolTracker { - writeKeyword(text: string): void; - writeOperator(text: string): void; - writePunctuation(text: string): void; - writeSpace(text: string): void; - writeStringLiteral(text: string): void; - writeParameter(text: string): void; - writeProperty(text: string): void; - writeSymbol(text: string, symbol: Symbol): void; - writeLine(): void; - increaseIndent(): void; - decreaseIndent(): void; - clear(): void; - } - enum SymbolAccessibility { - Accessible = 0, - NotAccessible = 1, - CannotBeNamed = 2 - } - enum SyntheticSymbolKind { - UnionOrIntersection = 0, - Spread = 1 - } enum TypePredicateKind { This = 0, Identifier = 1 @@ -2880,88 +2028,6 @@ declare namespace ts { parameterIndex: number; } type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; - type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration; - type AnyImportOrReExport = AnyImportSyntax | ExportDeclaration; - interface ValidImportTypeNode extends ImportTypeNode { - argument: LiteralTypeNode & { - literal: StringLiteral; - }; - } - type AnyValidImportOrReExport = (ImportDeclaration | ExportDeclaration) & { - moduleSpecifier: StringLiteral; - } | ImportEqualsDeclaration & { - moduleReference: ExternalModuleReference & { - expression: StringLiteral; - }; - } | RequireOrImportCall | ValidImportTypeNode; - type RequireOrImportCall = CallExpression & { - arguments: [StringLiteralLike]; - }; - type LateVisibilityPaintedStatement = AnyImportSyntax | VariableStatement | ClassDeclaration | FunctionDeclaration | ModuleDeclaration | TypeAliasDeclaration | InterfaceDeclaration | EnumDeclaration; - interface SymbolVisibilityResult { - accessibility: SymbolAccessibility; - aliasesToMakeVisible?: LateVisibilityPaintedStatement[]; - errorSymbolName?: string; - errorNode?: Node; - } - interface SymbolAccessibilityResult extends SymbolVisibilityResult { - errorModuleName?: string; - } - interface AllAccessorDeclarations { - firstAccessor: AccessorDeclaration; - secondAccessor: AccessorDeclaration | undefined; - getAccessor: AccessorDeclaration | undefined; - setAccessor: AccessorDeclaration | undefined; - } - /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */ - enum TypeReferenceSerializationKind { - Unknown = 0, - TypeWithConstructSignatureAndValue = 1, - VoidNullableOrNeverType = 2, - NumberLikeType = 3, - StringLikeType = 4, - BooleanType = 5, - ArrayLikeType = 6, - ESSymbolType = 7, - Promise = 8, - TypeWithCallSignature = 9, - ObjectType = 10 - } - interface EmitResolver { - hasGlobalName(name: string): boolean; - getReferencedExportContainer(node: Identifier, prefixLocals?: boolean): SourceFile | ModuleDeclaration | EnumDeclaration | undefined; - getReferencedImportDeclaration(node: Identifier): Declaration | undefined; - getReferencedDeclarationWithCollidingName(node: Identifier): Declaration | undefined; - isDeclarationWithCollidingName(node: Declaration): boolean; - isValueAliasDeclaration(node: Node): boolean; - isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean; - isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean; - getNodeCheckFlags(node: Node): NodeCheckFlags; - isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean; - isLateBound(node: Declaration): node is LateBoundDeclaration; - collectLinkedAliases(node: Identifier, setVisibility?: boolean): Node[] | undefined; - isImplementationOfOverload(node: FunctionLike): boolean | undefined; - isRequiredInitializedParameter(node: ParameterDeclaration): boolean; - isOptionalUninitializedParameterProperty(node: ParameterDeclaration): boolean; - createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean): TypeNode | undefined; - createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; - createTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; - createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): Expression; - isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags | undefined, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; - isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; - getReferencedValueDeclaration(reference: Identifier): Declaration | undefined; - getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind; - isOptionalParameter(node: ParameterDeclaration): boolean; - moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean; - isArgumentsLocalBinding(node: Identifier): boolean; - getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration | ImportTypeNode): SourceFile | undefined; - getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[] | undefined; - getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[] | undefined; - isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean; - getJsxFactoryEntity(location?: Node): EntityName | undefined; - getAllAccessorDeclarations(declaration: AccessorDeclaration): AllAccessorDeclarations; - } enum SymbolFlags { None = 0, FunctionScopedVariable = 1, @@ -2991,7 +2057,7 @@ declare namespace ts { Optional = 16777216, Transient = 33554432, JSContainer = 67108864, - All = 67108863, + ModuleExports = 134217728, Enum = 384, Variable = 3, Value = 67216319, @@ -3019,13 +2085,9 @@ declare namespace ts { AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, - HasExports = 1955, - HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - ClassMember = 106500, - Classifiable = 2885600, - LateBindingContainer = 6240 + ClassMember = 106500 } interface Symbol { flags: SymbolFlags; @@ -3035,72 +2097,6 @@ declare namespace ts { members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; - id?: number; - mergeId?: number; - parent?: Symbol; - exportSymbol?: Symbol; - nameType?: Type; - constEnumOnlyModule?: boolean; - isReferenced?: SymbolFlags; - isReplaceableByMethod?: boolean; - isAssigned?: boolean; - } - interface SymbolLinks { - immediateTarget?: Symbol; - target?: Symbol; - type?: Type; - uniqueESSymbolType?: Type; - declaredType?: Type; - typeParameters?: TypeParameter[]; - outerTypeParameters?: TypeParameter[]; - inferredClassType?: Type; - instantiations?: Map; - mapper?: TypeMapper; - referenced?: boolean; - containingType?: UnionOrIntersectionType; - leftSpread?: Symbol; - rightSpread?: Symbol; - syntheticOrigin?: Symbol; - isDiscriminantProperty?: boolean; - resolvedExports?: SymbolTable; - resolvedMembers?: SymbolTable; - exportsChecked?: boolean; - typeParametersChecked?: boolean; - isDeclarationWithCollidingName?: boolean; - bindingElement?: BindingElement; - exportsSomeValue?: boolean; - enumKind?: EnumKind; - originatingImport?: ImportDeclaration | ImportCall; - lateSymbol?: Symbol; - specifierCache?: Map; - } - enum EnumKind { - Numeric = 0, - Literal = 1 - } - enum CheckFlags { - Instantiated = 1, - SyntheticProperty = 2, - SyntheticMethod = 4, - Readonly = 8, - Partial = 16, - HasNonUniformType = 32, - ContainsPublic = 64, - ContainsProtected = 128, - ContainsPrivate = 256, - ContainsStatic = 512, - Late = 1024, - ReverseMapped = 2048, - OptionalParameter = 4096, - RestParameter = 8192, - Synthetic = 6 - } - interface TransientSymbol extends Symbol, SymbolLinks { - checkFlags: CheckFlags; - } - interface ReverseMappedSymbol extends TransientSymbol { - propertyType: Type; - mappedType: MappedType; } enum InternalSymbolName { Call = "__call", @@ -3118,7 +2114,8 @@ declare namespace ts { Computed = "__computed", Resolving = "__resolving__", ExportEquals = "export=", - Default = "default" + Default = "default", + This = "this" } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -3151,54 +2148,6 @@ declare namespace ts { } /** SymbolTable based on ES6 Map interface. */ type SymbolTable = UnderscoreEscapedMap; - /** Used to track a `declare module "foo*"`-like declaration. */ - interface PatternAmbientModule { - pattern: Pattern; - symbol: Symbol; - } - enum NodeCheckFlags { - TypeChecked = 1, - LexicalThis = 2, - CaptureThis = 4, - CaptureNewTarget = 8, - SuperInstance = 256, - SuperStatic = 512, - ContextChecked = 1024, - AsyncMethodWithSuper = 2048, - AsyncMethodWithSuperBinding = 4096, - CaptureArguments = 8192, - EnumValuesComputed = 16384, - LexicalModuleMergesWithClass = 32768, - LoopWithCapturedBlockScopedBinding = 65536, - CapturedBlockScopedBinding = 131072, - BlockScopedBindingInLoop = 262144, - ClassWithBodyScopedClassBinding = 524288, - BodyScopedClassBinding = 1048576, - NeedsLoopOutParameter = 2097152, - AssignmentsMarked = 4194304, - ClassWithConstructorReference = 8388608, - ConstructorReferenceInClass = 16777216 - } - interface NodeLinks { - flags: NodeCheckFlags; - resolvedType?: Type; - resolvedSignature?: Signature; - resolvedSignatures?: Map; - resolvedSymbol?: Symbol; - resolvedIndexInfo?: IndexInfo; - maybeTypePredicate?: boolean; - enumMemberValue?: string | number; - isVisible?: boolean; - containsArgumentsReference?: boolean; - hasReportedStatementInAmbientContext?: boolean; - jsxFlags: JsxFlags; - resolvedJsxElementAttributesType?: Type; - resolvedJsxElementAllAttributesType?: Type; - hasSuperCall?: boolean; - superCall?: SuperCall; - switchTypes?: Type[]; - jsxNamespace?: Symbol | false; - } enum TypeFlags { Any = 1, Unknown = 2, @@ -3225,28 +2174,16 @@ declare namespace ts { Conditional = 4194304, Substitution = 8388608, NonPrimitive = 16777216, - FreshLiteral = 33554432, - UnionOfUnitTypes = 67108864, - ContainsWideningType = 134217728, - ContainsObjectLiteral = 268435456, - ContainsAnyFunctionType = 536870912, - AnyOrUnknown = 3, - Nullable = 24576, Literal = 448, Unit = 27072, StringOrNumberLiteral = 192, - StringOrNumberLiteralOrUnique = 2240, - DefinitelyFalsy = 29120, PossiblyFalsy = 29148, - Intrinsic = 16839967, - Primitive = 32764, StringLike = 68, NumberLike = 168, BooleanLike = 272, EnumLike = 544, ESSymbolLike = 3072, VoidLike = 12288, - DisjointDomains = 16809468, UnionOrIntersection = 786432, StructuredType = 917504, TypeVariable = 2162688, @@ -3255,29 +2192,15 @@ declare namespace ts { Instantiable = 15794176, StructuredOrInstantiable = 16711680, Narrowable = 33492479, - NotUnionOrUnit = 16909315, - NotUnit = 16749629, - RequiresWidening = 402653184, - PropagatingFlags = 939524096, - NonWideningType = 134217728, - Wildcard = 268435456, - EmptyObject = 536870912, - ConstructionFlags = 939524096, - GenericMappedType = 134217728 + NotUnionOrUnit = 16909315 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { flags: TypeFlags; - id: number; - checker: TypeChecker; symbol: Symbol; pattern?: DestructuringPattern; aliasSymbol?: Symbol; aliasTypeArguments?: ReadonlyArray; - wildcardInstantiation?: Type; - } - interface IntrinsicType extends Type { - intrinsicName: string; } interface LiteralType extends Type { value: string | number; @@ -3310,16 +2233,11 @@ declare namespace ts { ReverseMapped = 2048, JsxAttributes = 4096, MarkerType = 8192, + JSLiteral = 16384, ClassOrInterface = 3 } interface ObjectType extends Type { objectFlags: ObjectFlags; - members?: SymbolTable; - properties?: Symbol[]; - callSignatures?: ReadonlyArray; - constructSignatures?: ReadonlyArray; - stringIndexInfo?: IndexInfo; - numberIndexInfo?: IndexInfo; } /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ interface InterfaceType extends ObjectType { @@ -3327,8 +2245,6 @@ declare namespace ts { outerTypeParameters: TypeParameter[] | undefined; localTypeParameters: TypeParameter[] | undefined; thisType: TypeParameter | undefined; - resolvedBaseConstructorType?: Type; - resolvedBaseTypes: BaseType[]; } type BaseType = ObjectType | IntersectionType; interface InterfaceTypeWithDeclaredMembers extends InterfaceType { @@ -3352,16 +2268,7 @@ declare namespace ts { target: GenericType; typeArguments?: ReadonlyArray; } - enum Variance { - Invariant = 0, - Covariant = 1, - Contravariant = 2, - Bivariant = 3, - Independent = 4 - } interface GenericType extends InterfaceType, TypeReference { - instantiations: Map; - variances?: Variance[]; } interface TupleType extends GenericType { minLength: number; @@ -3373,74 +2280,19 @@ declare namespace ts { } interface UnionOrIntersectionType extends Type { types: Type[]; - propertyCache: SymbolTable; - resolvedProperties: Symbol[]; - resolvedIndexType: IndexType; - resolvedStringIndexType: IndexType; - resolvedBaseConstraint: Type; - couldContainTypeVariables: boolean; } interface UnionType extends UnionOrIntersectionType { } interface IntersectionType extends UnionOrIntersectionType { - resolvedApparentType: Type; } type StructuredType = ObjectType | UnionType | IntersectionType; - interface AnonymousType extends ObjectType { - target?: AnonymousType; - mapper?: TypeMapper; - } - interface MappedType extends AnonymousType { - declaration: MappedTypeNode; - typeParameter?: TypeParameter; - constraintType?: Type; - templateType?: Type; - modifiersType?: Type; - } interface EvolvingArrayType extends ObjectType { elementType: Type; finalArrayType?: Type; } - interface ReverseMappedType extends ObjectType { - source: Type; - mappedType: MappedType; - } - interface ResolvedType extends ObjectType, UnionOrIntersectionType { - members: SymbolTable; - properties: Symbol[]; - callSignatures: ReadonlyArray; - constructSignatures: ReadonlyArray; - } - interface FreshObjectLiteralType extends ResolvedType { - regularType: ResolvedType; - } - interface IterableOrIteratorType extends ObjectType, UnionType { - iteratedTypeOfIterable?: Type; - iteratedTypeOfIterator?: Type; - iteratedTypeOfAsyncIterable?: Type; - iteratedTypeOfAsyncIterator?: Type; - } - interface PromiseOrAwaitableType extends ObjectType, UnionType { - promiseTypeOfPromiseConstructor?: Type; - promisedTypeOfPromise?: Type; - awaitedTypeOfType?: Type; - } - interface SyntheticDefaultModuleType extends Type { - syntheticType?: Type; - } interface InstantiableType extends Type { - resolvedBaseConstraint?: Type; - resolvedIndexType?: IndexType; - resolvedStringIndexType?: IndexType; } interface TypeParameter extends InstantiableType { - /** Retrieve using getConstraintFromTypeParameter */ - constraint?: Type; - default?: Type; - target?: TypeParameter; - mapper?: TypeMapper; - isThisType?: boolean; - resolvedDefaultType?: Type; } interface IndexedAccessType extends InstantiableType { objectType: Type; @@ -3451,7 +2303,6 @@ declare namespace ts { type TypeVariable = TypeParameter | IndexedAccessType; interface IndexType extends InstantiableType { type: InstantiableType | UnionOrIntersectionType; - stringsOnly: boolean; } interface ConditionalRoot { node: ConditionalTypeNode; @@ -3472,9 +2323,6 @@ declare namespace ts { extendsType: Type; resolvedTrueType?: Type; resolvedFalseType?: Type; - resolvedDefaultConstraint?: Type; - mapper?: TypeMapper; - combinedMapper?: TypeMapper; } interface SubstitutionType extends InstantiableType { typeVariable: TypeVariable; @@ -3488,19 +2336,6 @@ declare namespace ts { declaration?: SignatureDeclaration | JSDocSignature; typeParameters?: ReadonlyArray; parameters: ReadonlyArray; - thisParameter?: Symbol; - resolvedReturnType?: Type; - resolvedTypePredicate?: TypePredicate; - minArgumentCount: number; - hasRestParameter: boolean; - hasLiteralTypes: boolean; - target?: Signature; - mapper?: TypeMapper; - unionSignatures?: Signature[]; - erasedSignatureCache?: Signature; - canonicalSignatureCache?: Signature; - isolatedSignatureType?: ObjectType; - instantiations?: Map; } enum IndexKind { String = 0, @@ -3511,7 +2346,6 @@ declare namespace ts { isReadonly: boolean; declaration?: IndexSignatureDeclaration; } - type TypeMapper = (t: TypeParameter) => Type; enum InferencePriority { NakedTypeVariable = 1, HomomorphicMappedType = 2, @@ -3522,58 +2356,6 @@ declare namespace ts { AlwaysStrict = 64, PriorityImpliesCombination = 28 } - interface InferenceInfo { - typeParameter: TypeParameter; - candidates: Type[] | undefined; - contraCandidates: Type[] | undefined; - inferredType?: Type; - priority?: InferencePriority; - topLevel: boolean; - isFixed: boolean; - } - enum InferenceFlags { - None = 0, - InferUnionTypes = 1, - NoDefault = 2, - AnyDefault = 4 - } - /** - * Ternary values are defined such that - * x & y is False if either x or y is False. - * x & y is Maybe if either x or y is Maybe, but neither x or y is False. - * x & y is True if both x and y are True. - * x | y is False if both x and y are False. - * x | y is Maybe if either x or y is Maybe, but neither x or y is True. - * x | y is True if either x or y is True. - */ - enum Ternary { - False = 0, - Maybe = 1, - True = -1 - } - type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary; - interface InferenceContext extends TypeMapper { - typeParameters: ReadonlyArray; - signature?: Signature; - inferences: InferenceInfo[]; - flags: InferenceFlags; - compareTypes: TypeComparer; - } - interface WideningContext { - parent?: WideningContext; - propertyName?: __String; - siblings?: Type[]; - resolvedProperties?: Symbol[]; - } - enum SpecialPropertyAssignmentKind { - None = 0, - ExportsProperty = 1, - ModuleExports = 2, - PrototypeProperty = 3, - ThisProperty = 4, - Property = 5, - Prototype = 6 - } /** @deprecated Use FileExtensionInfo instead. */ type JsFileExtensionInfo = FileExtensionInfo; interface FileExtensionInfo { @@ -3625,9 +2407,6 @@ declare namespace ts { Suggestion = 2, Message = 3 } - function diagnosticCategoryName(d: { - category: DiagnosticCategory; - }, lowerCase?: boolean): string; enum ModuleResolutionKind { Classic = 1, NodeJs = 2 @@ -3647,44 +2426,31 @@ declare namespace ts { } type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; interface CompilerOptions { - all?: boolean; allowJs?: boolean; - allowNonTsExtensions?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; alwaysStrict?: boolean; baseUrl?: string; - /** An error if set - this should only go through the -b pipeline and not actually be observed */ - build?: boolean; charset?: string; checkJs?: boolean; - configFilePath?: string; - /** configFile is set as non enumerable property so as to avoid checking of json source files */ - readonly configFile?: TsConfigSourceFile; declaration?: boolean; declarationMap?: boolean; emitDeclarationOnly?: boolean; declarationDir?: string; - diagnostics?: boolean; - extendedDiagnostics?: boolean; disableSizeLimit?: boolean; downlevelIteration?: boolean; emitBOM?: boolean; emitDecoratorMetadata?: boolean; experimentalDecorators?: boolean; forceConsistentCasingInFileNames?: boolean; - help?: boolean; importHelpers?: boolean; - init?: boolean; inlineSourceMap?: boolean; inlineSources?: boolean; isolatedModules?: boolean; jsx?: JsxEmit; keyofStringsOnly?: boolean; lib?: string[]; - listEmittedFiles?: boolean; - listFiles?: boolean; locale?: string; mapRoot?: string; maxNodeModuleJsDepth?: number; @@ -3692,7 +2458,6 @@ declare namespace ts { moduleResolution?: ModuleResolutionKind; newLine?: NewLineKind; noEmit?: boolean; - noEmitForJsFiles?: boolean; noEmitHelpers?: boolean; noEmitOnError?: boolean; noErrorTruncation?: boolean; @@ -3710,12 +2475,9 @@ declare namespace ts { outDir?: string; outFile?: string; paths?: MapLike; - plugins?: PluginImport[]; preserveConstEnums?: boolean; preserveSymlinks?: boolean; - preserveWatchOutput?: boolean; project?: string; - pretty?: boolean; reactNamespace?: string; jsxFactory?: string; composite?: boolean; @@ -3733,15 +2495,12 @@ declare namespace ts { stripInternal?: boolean; suppressExcessPropertyErrors?: boolean; suppressImplicitAnyIndexErrors?: boolean; - suppressOutputPathCheck?: boolean; target?: ScriptTarget; traceResolution?: boolean; resolveJsonModule?: boolean; types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; - version?: boolean; - watch?: boolean; esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; } @@ -3815,32 +2574,15 @@ declare namespace ts { errors: Diagnostic[]; wildcardDirectories?: MapLike; compileOnSave?: boolean; - configFileSpecs?: ConfigFileSpecs; } enum WatchDirectoryFlags { None = 0, Recursive = 1 } - interface ConfigFileSpecs { - filesSpecs: ReadonlyArray | undefined; - referencesSpecs: ReadonlyArray | undefined; - /** - * Present to report errors (user specified specs), validatedIncludeSpecs are used for file name matching - */ - includeSpecs?: ReadonlyArray; - /** - * Present to report errors (user specified specs), validatedExcludeSpecs are used for file name matching - */ - excludeSpecs?: ReadonlyArray; - validatedIncludeSpecs?: ReadonlyArray; - validatedExcludeSpecs?: ReadonlyArray; - wildcardDirectories: MapLike; - } interface ExpandResult { fileNames: string[]; projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; - spec: ConfigFileSpecs; } interface CreateProgramOptions { rootNames: ReadonlyArray; @@ -3850,163 +2592,9 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface CommandLineOptionBase { - name: string; - type: "string" | "number" | "boolean" | "object" | "list" | Map; - isFilePath?: boolean; - shortName?: string; - description?: DiagnosticMessage; - paramType?: DiagnosticMessage; - isTSConfigOnly?: boolean; - isCommandLineOnly?: boolean; - showInSimplifiedHelpView?: boolean; - category?: DiagnosticMessage; - } - interface CommandLineOptionOfPrimitiveType extends CommandLineOptionBase { - type: "string" | "number" | "boolean"; - } - interface CommandLineOptionOfCustomType extends CommandLineOptionBase { - type: Map; - } - interface TsConfigOnlyOption extends CommandLineOptionBase { - type: "object"; - elementOptions?: Map; - extraKeyDiagnosticMessage?: DiagnosticMessage; - } - interface CommandLineOptionOfListType extends CommandLineOptionBase { - type: "list"; - element: CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption; - } - type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption | CommandLineOptionOfListType; - enum CharacterCodes { - nullCharacter = 0, - maxAsciiCharacter = 127, - lineFeed = 10, - carriageReturn = 13, - lineSeparator = 8232, - paragraphSeparator = 8233, - nextLine = 133, - space = 32, - nonBreakingSpace = 160, - enQuad = 8192, - emQuad = 8193, - enSpace = 8194, - emSpace = 8195, - threePerEmSpace = 8196, - fourPerEmSpace = 8197, - sixPerEmSpace = 8198, - figureSpace = 8199, - punctuationSpace = 8200, - thinSpace = 8201, - hairSpace = 8202, - zeroWidthSpace = 8203, - narrowNoBreakSpace = 8239, - ideographicSpace = 12288, - mathematicalSpace = 8287, - ogham = 5760, - _ = 95, - $ = 36, - _0 = 48, - _1 = 49, - _2 = 50, - _3 = 51, - _4 = 52, - _5 = 53, - _6 = 54, - _7 = 55, - _8 = 56, - _9 = 57, - a = 97, - b = 98, - c = 99, - d = 100, - e = 101, - f = 102, - g = 103, - h = 104, - i = 105, - j = 106, - k = 107, - l = 108, - m = 109, - n = 110, - o = 111, - p = 112, - q = 113, - r = 114, - s = 115, - t = 116, - u = 117, - v = 118, - w = 119, - x = 120, - y = 121, - z = 122, - A = 65, - B = 66, - C = 67, - D = 68, - E = 69, - F = 70, - G = 71, - H = 72, - I = 73, - J = 74, - K = 75, - L = 76, - M = 77, - N = 78, - O = 79, - P = 80, - Q = 81, - R = 82, - S = 83, - T = 84, - U = 85, - V = 86, - W = 87, - X = 88, - Y = 89, - Z = 90, - ampersand = 38, - asterisk = 42, - at = 64, - backslash = 92, - backtick = 96, - bar = 124, - caret = 94, - closeBrace = 125, - closeBracket = 93, - closeParen = 41, - colon = 58, - comma = 44, - dot = 46, - doubleQuote = 34, - equals = 61, - exclamation = 33, - greaterThan = 62, - hash = 35, - lessThan = 60, - minus = 45, - openBrace = 123, - openBracket = 91, - openParen = 40, - percent = 37, - plus = 43, - question = 63, - semicolon = 59, - singleQuote = 39, - slash = 47, - tilde = 126, - backspace = 8, - formFeed = 12, - byteOrderMark = 65279, - tab = 9, - verticalTab = 11 - } interface UpToDateHost { fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date; + getModifiedTime(fileName: string): Date | undefined; getUnchangedTime?(fileName: string): Date | undefined; getLastStatus?(fileName: string): UpToDateStatus | undefined; setLastStatus?(fileName: string, status: UpToDateStatus): void; @@ -4044,7 +2632,6 @@ declare namespace ts { * If changing this, remember to change `moduleResolutionIsEqualTo`. */ interface ResolvedModuleFull extends ResolvedModule { - readonly originalPath?: string; /** * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. * This is optional for backwards-compatibility, but will be added if not provided. @@ -4081,7 +2668,6 @@ declare namespace ts { } interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; - readonly failedLookupLocations: ReadonlyArray; } interface ResolvedTypeReferenceDirective { primary: boolean; @@ -4092,7 +2678,6 @@ declare namespace ts { readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; readonly failedLookupLocations: ReadonlyArray; } - type HasInvalidatedResolution = (sourceFile: Path) => boolean; interface CompilerHost extends ModuleResolutionHost { getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; @@ -4112,97 +2697,19 @@ declare namespace ts { */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; - onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions): void; - hasInvalidatedResolution?: HasInvalidatedResolution; - hasChangedAutomaticTypeDirectiveNames?: boolean; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date; + getModifiedTime?(fileName: string): Date | undefined; setModifiedTime?(fileName: string, date: Date): void; deleteFile?(fileName: string): void; } - enum TransformFlags { - None = 0, - TypeScript = 1, - ContainsTypeScript = 2, - ContainsJsx = 4, - ContainsESNext = 8, - ContainsES2017 = 16, - ContainsES2016 = 32, - ES2015 = 64, - ContainsES2015 = 128, - Generator = 256, - ContainsGenerator = 512, - DestructuringAssignment = 1024, - ContainsDestructuringAssignment = 2048, - ContainsDecorators = 4096, - ContainsPropertyInitializer = 8192, - ContainsLexicalThis = 16384, - ContainsCapturedLexicalThis = 32768, - ContainsLexicalThisInComputedPropertyName = 65536, - ContainsDefaultValueAssignments = 131072, - ContainsParameterPropertyAssignments = 262144, - ContainsSpread = 524288, - ContainsObjectSpread = 1048576, - ContainsRest = 524288, - ContainsObjectRest = 1048576, - ContainsComputedPropertyName = 2097152, - ContainsBlockScopedBinding = 4194304, - ContainsBindingPattern = 8388608, - ContainsYield = 16777216, - ContainsHoistedDeclarationOrCompletion = 33554432, - ContainsDynamicImport = 67108864, - Super = 134217728, - ContainsSuper = 268435456, - HasComputedFlags = 536870912, - AssertTypeScript = 3, - AssertJsx = 4, - AssertESNext = 8, - AssertES2017 = 16, - AssertES2016 = 32, - AssertES2015 = 192, - AssertGenerator = 768, - AssertDestructuringAssignment = 3072, - OuterExpressionExcludes = 536872257, - PropertyAccessExcludes = 671089985, - NodeExcludes = 939525441, - ArrowFunctionExcludes = 1003902273, - FunctionExcludes = 1003935041, - ConstructorExcludes = 1003668801, - MethodOrAccessorExcludes = 1003668801, - ClassExcludes = 942011713, - ModuleExcludes = 977327425, - TypeExcludes = -3, - ObjectLiteralExcludes = 942740801, - ArrayLiteralOrCallOrNewExcludes = 940049729, - VariableDeclarationListExcludes = 948962625, - ParameterExcludes = 939525441, - CatchClauseExcludes = 940574017, - BindingPatternExcludes = 940049729, - TypeScriptClassSyntaxMask = 274432, - ES2015FunctionSyntaxMask = 163840 - } interface SourceMapRange extends TextRange { source?: SourceMapSource; } interface SourceMapSource { fileName: string; text: string; - lineMap: ReadonlyArray; skipTrivia?: (pos: number) => number; } - interface EmitNode { - annotatedNodes?: Node[]; - flags: EmitFlags; - leadingComments?: SynthesizedComment[]; - trailingComments?: SynthesizedComment[]; - commentRange?: TextRange; - sourceMapRange?: SourceMapRange; - tokenSourceMapRanges?: (SourceMapRange | undefined)[]; - constantValue?: string | number; - externalHelpersModuleName?: Identifier; - helpers?: EmitHelper[]; - startsOnNewLine?: boolean; - } enum EmitFlags { None = 0, SingleLine = 1, @@ -4232,9 +2739,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, - NoAsciiEscaping = 16777216, - TypeScriptClassWrapper = 33554432, - NeverApplyImportHelper = 67108864 + NoAsciiEscaping = 16777216 } interface EmitHelper { readonly name: string; @@ -4242,38 +2747,7 @@ declare namespace ts { readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); readonly priority?: number; } - type UniqueNameHandler = (baseName: string, checkFn?: (name: string) => boolean, optimistic?: boolean) => string; type EmitHelperUniqueNameCallback = (name: string) => string; - /** - * Used by the checker, this enum keeps track of external emit helpers that should be type - * checked. - */ - enum ExternalEmitHelpers { - Extends = 1, - Assign = 2, - Rest = 4, - Decorate = 8, - Metadata = 16, - Param = 32, - Awaiter = 64, - Generator = 128, - Values = 256, - Read = 512, - Spread = 1024, - Await = 2048, - AsyncGenerator = 4096, - AsyncDelegator = 8192, - AsyncValues = 16384, - ExportStar = 32768, - MakeTemplateObject = 65536, - FirstEmitHelper = 1, - LastEmitHelper = 65536, - ForOfIncludes = 256, - ForAwaitOfIncludes = 16384, - AsyncGeneratorIncludes = 6144, - AsyncDelegatorIncludes = 26624, - SpreadIncludes = 1536 - } enum EmitHint { SourceFile = 0, Expression = 1, @@ -4281,21 +2755,7 @@ declare namespace ts { MappedTypeParameter = 3, Unspecified = 4 } - interface EmitHost extends ScriptReferenceHost, ModuleSpecifierResolutionHost { - getSourceFiles(): ReadonlyArray; - useCaseSensitiveFileNames(): boolean; - getCurrentDirectory(): string; - isSourceFileFromExternalLibrary(file: SourceFile): boolean; - getCommonSourceDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - isEmitBlocked(emitFileName: string): boolean; - getPrependNodes(): ReadonlyArray; - writeFile: WriteFileCallback; - } interface TransformationContext { - getEmitResolver(): EmitResolver; - getEmitHost(): EmitHost; /** Gets the compiler options supplied to the transformer. */ getCompilerOptions(): CompilerOptions; /** Starts a new lexical environment. */ @@ -4344,7 +2804,6 @@ declare namespace ts { * before returning the `NodeTransformer` callback. */ onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; - addDiagnostic(diag: DiagnosticWithLocation): void; } interface TransformationResult { /** Gets the transformed source files. */ @@ -4412,20 +2871,6 @@ declare namespace ts { * Prints a bundle of source files as-is, without any emit transformations. */ printBundle(bundle: Bundle): string; - writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void; - writeList(format: ListFormat, list: NodeArray | undefined, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void; - writeFile(sourceFile: SourceFile, writer: EmitTextWriter): void; - writeBundle(bundle: Bundle, writer: EmitTextWriter, info?: BundleInfo): void; - } - /** - * When a bundle contains prepended content, we store a file on disk indicating where the non-prepended - * content of that file starts. On a subsequent build where there are no upstream .d.ts changes, we - * read the bundle info file and the original .js file to quickly re-use portion of the file - * that didn't originate in prepended content. - */ - interface BundleInfo { - originalOffset: number; - totalLength: number; } interface PrintHandlers { /** @@ -4469,58 +2914,17 @@ declare namespace ts { * ``` */ substituteNode?(hint: EmitHint, node: Node): Node; - onEmitSourceMapOfNode?: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; - onEmitSourceMapOfToken?: (node: Node | undefined, token: SyntaxKind, writer: (s: string) => void, pos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, pos: number) => number) => number; - onEmitSourceMapOfPosition?: (pos: number) => void; - onSetSourceFile?: (node: SourceFile) => void; - onBeforeEmitNodeArray?: (nodes: NodeArray | undefined) => void; - onAfterEmitNodeArray?: (nodes: NodeArray | undefined) => void; - onBeforeEmitToken?: (node: Node) => void; - onAfterEmitToken?: (node: Node) => void; } interface PrinterOptions { removeComments?: boolean; newLine?: NewLineKind; omitTrailingSemicolon?: boolean; noEmitHelpers?: boolean; - module?: CompilerOptions["module"]; - target?: CompilerOptions["target"]; - sourceMap?: boolean; - inlineSourceMap?: boolean; - extendedDiagnostics?: boolean; - onlyPrintJsDocStyle?: boolean; - } - interface EmitTextWriter extends SymbolWriter { - write(s: string): void; - writeTextOfNode(text: string, node: Node): void; - getText(): string; - rawWrite(s: string): void; - writeLiteral(s: string): void; - getTextPos(): number; - getLine(): number; - getColumn(): number; - getIndent(): number; - isAtStartOfLine(): boolean; } interface GetEffectiveTypeRootsHost { directoryExists?(directoryName: string): boolean; getCurrentDirectory?(): string; } - /** @internal */ - interface ModuleSpecifierResolutionHost extends GetEffectiveTypeRootsHost { - useCaseSensitiveFileNames?(): boolean; - fileExists?(path: string): boolean; - readFile?(path: string): string | undefined; - getSourceFiles?(): ReadonlyArray; - } - interface SymbolTracker { - trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - reportInaccessibleThisError?(): void; - reportPrivateInBaseOfClassExpression?(propertyName: string): void; - reportInaccessibleUniqueSymbolError?(): void; - moduleResolverHost?: ModuleSpecifierResolutionHost; - trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void; - } interface TextSpan { start: number; length: number; @@ -4529,14 +2933,6 @@ declare namespace ts { span: TextSpan; newLength: number; } - interface DiagnosticCollection { - add(diagnostic: Diagnostic): void; - lookup(diagnostic: Diagnostic): Diagnostic | undefined; - getGlobalDiagnostics(): Diagnostic[]; - getDiagnostics(fileName: string): DiagnosticWithLocation[]; - getDiagnostics(): Diagnostic[]; - reattachFileDiagnostics(newFile: SourceFile): void; - } interface SyntaxList extends Node { _children: Node[]; } @@ -4605,145 +3001,10 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } - enum PragmaKindFlags { - None = 0, - /** - * Triple slash comment of the form - * /// - */ - TripleSlashXML = 1, - /** - * Single line comment of the form - * // @pragma-name argval1 argval2 - * or - * /// @pragma-name argval1 argval2 - */ - SingleLine = 2, - /** - * Multiline non-jsdoc pragma of the form - * /* @pragma-name argval1 argval2 * / - */ - MultiLine = 4, - All = 7, - Default = 7 - } - interface PragmaArgumentSpecification { - name: TName; - optional?: boolean; - captureSpan?: boolean; - } - interface PragmaDefinition { - args?: [PragmaArgumentSpecification] | [PragmaArgumentSpecification, PragmaArgumentSpecification] | [PragmaArgumentSpecification, PragmaArgumentSpecification, PragmaArgumentSpecification] | [PragmaArgumentSpecification, PragmaArgumentSpecification, PragmaArgumentSpecification, PragmaArgumentSpecification]; - kind?: PragmaKindFlags; - } - const commentPragmas: { - "reference": { - args: [{ - name: "types"; - optional: true; - captureSpan: true; - }, { - name: "lib"; - optional: true; - captureSpan: true; - }, { - name: "path"; - optional: true; - captureSpan: true; - }, { - name: "no-default-lib"; - optional: true; - }]; - kind: PragmaKindFlags; - }; - "amd-dependency": { - args: [{ - name: "path"; - }, { - name: "name"; - optional: true; - }]; - kind: PragmaKindFlags; - }; - "amd-module": { - args: [{ - name: "name"; - }]; - kind: PragmaKindFlags; - }; - "ts-check": { - kind: PragmaKindFlags; - }; - "ts-nocheck": { - kind: PragmaKindFlags; - }; - "jsx": { - args: [{ - name: "factory"; - }]; - kind: PragmaKindFlags; - }; - }; - type PragmaArgTypeMaybeCapture = TDesc extends { - captureSpan: true; - } ? { - value: string; - pos: number; - end: number; - } : string; - type PragmaArgTypeOptional = TDesc extends { - optional: true; - } ? { - [K in TName]?: PragmaArgTypeMaybeCapture; - } : { - [K in TName]: PragmaArgTypeMaybeCapture; - }; - /** - * Maps a pragma definition into the desired shape for its arguments object - * Maybe the below is a good argument for types being iterable on struture in some way. - */ - type PragmaArgumentType = T extends { - args: [PragmaArgumentSpecification, PragmaArgumentSpecification, PragmaArgumentSpecification, PragmaArgumentSpecification]; - } ? PragmaArgTypeOptional & PragmaArgTypeOptional & PragmaArgTypeOptional & PragmaArgTypeOptional : T extends { - args: [PragmaArgumentSpecification, PragmaArgumentSpecification, PragmaArgumentSpecification]; - } ? PragmaArgTypeOptional & PragmaArgTypeOptional & PragmaArgTypeOptional : T extends { - args: [PragmaArgumentSpecification, PragmaArgumentSpecification]; - } ? PragmaArgTypeOptional & PragmaArgTypeOptional : T extends { - args: [PragmaArgumentSpecification]; - } ? PragmaArgTypeOptional : object; - type ConcretePragmaSpecs = typeof commentPragmas; - type PragmaPsuedoMap = { - [K in keyof ConcretePragmaSpecs]?: { - arguments: PragmaArgumentType; - range: CommentRange; - }; - }; - type PragmaPsuedoMapEntry = { - [K in keyof PragmaPsuedoMap]: { - name: K; - args: PragmaPsuedoMap[K]; - }; - }[keyof PragmaPsuedoMap]; - /** - * A strongly-typed es6 map of pragma entries, the values of which are either a single argument - * value (if only one was found), or an array of multiple argument values if the pragma is present - * in multiple places - */ - interface PragmaMap extends Map { - set(key: TKey, value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]): this; - get(key: TKey): PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][]; - forEach(action: (value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][], key: TKey) => void): void; - } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; declare namespace ts { - /** - * Set a high stack trace limit to provide more information in case of an error. - * Called for command-line and server use cases. - * Not called if TypeScript is used as a library. - */ - function setStackTraceLimit(): void; enum FileWatcherEventKind { Created = 0, Changed = 1, @@ -4751,47 +3012,6 @@ declare namespace ts { } type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; - interface WatchedFile { - readonly fileName: string; - readonly callback: FileWatcherCallback; - mtime: Date; - } - enum PollingInterval { - High = 2000, - Medium = 500, - Low = 250 - } - function watchFileUsingPriorityPollingInterval(host: System, fileName: string, callback: FileWatcherCallback, watchPriority: PollingInterval): FileWatcher; - type HostWatchFile = (fileName: string, callback: FileWatcherCallback, pollingInterval: PollingInterval | undefined) => FileWatcher; - type HostWatchDirectory = (fileName: string, callback: DirectoryWatcherCallback, recursive?: boolean) => FileWatcher; - const missingFileModifiedTime: Date; - let unchangedPollThresholds: { - [PollingInterval.Low]: number; - [PollingInterval.Medium]: number; - [PollingInterval.High]: number; - }; - function setCustomPollingValues(system: System): void; - function createDynamicPriorityPollingWatchFile(host: { - getModifiedTime: System["getModifiedTime"]; - setTimeout: System["setTimeout"]; - }): HostWatchFile; - /** - * Returns true if file status changed - */ - function onWatchedFileStat(watchedFile: WatchedFile, modifiedTime: Date): boolean; - interface RecursiveDirectoryWatcherHost { - watchDirectory: HostWatchDirectory; - getAccessibleSortedChildDirectories(path: string): ReadonlyArray; - directoryExists(dir: string): boolean; - filePathComparer: Comparer; - realpath(s: string): string; - } - /** - * Watch the directory recursively using host provided method to watch child directories - * that means if this is recursive watcher, watch the children directories as well - * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile) - */ - function createRecursiveDirectoryWatcher(host: RecursiveDirectoryWatcherHost): (directoryName: string, callback: DirectoryWatcherCallback) => FileWatcher; interface System { args: string[]; newLine: string; @@ -4815,7 +3035,7 @@ declare namespace ts { getCurrentDirectory(): string; getDirectories(path: string): string[]; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - getModifiedTime?(path: string): Date; + getModifiedTime?(path: string): Date | undefined; setModifiedTime?(path: string, time: Date): void; deleteFile?(path: string): void; /** @@ -4827,13 +3047,9 @@ declare namespace ts { getMemoryUsage?(): number; exit(exitCode?: number): void; realpath?(path: string): string; - getEnvironmentVariable(name: string): string; - tryEnableSourceMapsForHost?(): void; - debugMode?: boolean; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; clearScreen?(): void; - setBlocking?(): void; base64decode?(input: string): string; base64encode?(input: string): string; } @@ -4843,1132 +3059,8 @@ declare namespace ts { function getNodeMajorVersion(): number | undefined; let sys: System; } -declare namespace ts { - const Diagnostics: { - Unterminated_string_literal: DiagnosticMessage; - Identifier_expected: DiagnosticMessage; - _0_expected: DiagnosticMessage; - A_file_cannot_have_a_reference_to_itself: DiagnosticMessage; - Trailing_comma_not_allowed: DiagnosticMessage; - Asterisk_Slash_expected: DiagnosticMessage; - An_element_access_expression_should_take_an_argument: DiagnosticMessage; - Unexpected_token: DiagnosticMessage; - A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: DiagnosticMessage; - A_rest_parameter_must_be_last_in_a_parameter_list: DiagnosticMessage; - Parameter_cannot_have_question_mark_and_initializer: DiagnosticMessage; - A_required_parameter_cannot_follow_an_optional_parameter: DiagnosticMessage; - An_index_signature_cannot_have_a_rest_parameter: DiagnosticMessage; - An_index_signature_parameter_cannot_have_an_accessibility_modifier: DiagnosticMessage; - An_index_signature_parameter_cannot_have_a_question_mark: DiagnosticMessage; - An_index_signature_parameter_cannot_have_an_initializer: DiagnosticMessage; - An_index_signature_must_have_a_type_annotation: DiagnosticMessage; - An_index_signature_parameter_must_have_a_type_annotation: DiagnosticMessage; - An_index_signature_parameter_type_must_be_string_or_number: DiagnosticMessage; - readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: DiagnosticMessage; - Accessibility_modifier_already_seen: DiagnosticMessage; - _0_modifier_must_precede_1_modifier: DiagnosticMessage; - _0_modifier_already_seen: DiagnosticMessage; - _0_modifier_cannot_appear_on_a_class_element: DiagnosticMessage; - super_must_be_followed_by_an_argument_list_or_member_access: DiagnosticMessage; - Only_ambient_modules_can_use_quoted_names: DiagnosticMessage; - Statements_are_not_allowed_in_ambient_contexts: DiagnosticMessage; - A_declare_modifier_cannot_be_used_in_an_already_ambient_context: DiagnosticMessage; - Initializers_are_not_allowed_in_ambient_contexts: DiagnosticMessage; - _0_modifier_cannot_be_used_in_an_ambient_context: DiagnosticMessage; - _0_modifier_cannot_be_used_with_a_class_declaration: DiagnosticMessage; - _0_modifier_cannot_be_used_here: DiagnosticMessage; - _0_modifier_cannot_appear_on_a_data_property: DiagnosticMessage; - _0_modifier_cannot_appear_on_a_module_or_namespace_element: DiagnosticMessage; - A_0_modifier_cannot_be_used_with_an_interface_declaration: DiagnosticMessage; - A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: DiagnosticMessage; - A_rest_parameter_cannot_be_optional: DiagnosticMessage; - A_rest_parameter_cannot_have_an_initializer: DiagnosticMessage; - A_set_accessor_must_have_exactly_one_parameter: DiagnosticMessage; - A_set_accessor_cannot_have_an_optional_parameter: DiagnosticMessage; - A_set_accessor_parameter_cannot_have_an_initializer: DiagnosticMessage; - A_set_accessor_cannot_have_rest_parameter: DiagnosticMessage; - A_get_accessor_cannot_have_parameters: DiagnosticMessage; - Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: DiagnosticMessage; - Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: DiagnosticMessage; - An_async_function_or_method_must_have_a_valid_awaitable_return_type: DiagnosticMessage; - The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: DiagnosticMessage; - A_promise_must_have_a_then_method: DiagnosticMessage; - The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: DiagnosticMessage; - Enum_member_must_have_initializer: DiagnosticMessage; - Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: DiagnosticMessage; - An_export_assignment_cannot_be_used_in_a_namespace: DiagnosticMessage; - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: DiagnosticMessage; - In_ambient_enum_declarations_member_initializer_must_be_constant_expression: DiagnosticMessage; - Unexpected_token_A_constructor_method_accessor_or_property_was_expected: DiagnosticMessage; - Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: DiagnosticMessage; - _0_modifier_cannot_appear_on_a_type_member: DiagnosticMessage; - _0_modifier_cannot_appear_on_an_index_signature: DiagnosticMessage; - A_0_modifier_cannot_be_used_with_an_import_declaration: DiagnosticMessage; - Invalid_reference_directive_syntax: DiagnosticMessage; - Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: DiagnosticMessage; - An_accessor_cannot_be_declared_in_an_ambient_context: DiagnosticMessage; - _0_modifier_cannot_appear_on_a_constructor_declaration: DiagnosticMessage; - _0_modifier_cannot_appear_on_a_parameter: DiagnosticMessage; - Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: DiagnosticMessage; - Type_parameters_cannot_appear_on_a_constructor_declaration: DiagnosticMessage; - Type_annotation_cannot_appear_on_a_constructor_declaration: DiagnosticMessage; - An_accessor_cannot_have_type_parameters: DiagnosticMessage; - A_set_accessor_cannot_have_a_return_type_annotation: DiagnosticMessage; - An_index_signature_must_have_exactly_one_parameter: DiagnosticMessage; - _0_list_cannot_be_empty: DiagnosticMessage; - Type_parameter_list_cannot_be_empty: DiagnosticMessage; - Type_argument_list_cannot_be_empty: DiagnosticMessage; - Invalid_use_of_0_in_strict_mode: DiagnosticMessage; - with_statements_are_not_allowed_in_strict_mode: DiagnosticMessage; - delete_cannot_be_called_on_an_identifier_in_strict_mode: DiagnosticMessage; - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: DiagnosticMessage; - A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: DiagnosticMessage; - A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: DiagnosticMessage; - Jump_target_cannot_cross_function_boundary: DiagnosticMessage; - A_return_statement_can_only_be_used_within_a_function_body: DiagnosticMessage; - Expression_expected: DiagnosticMessage; - Type_expected: DiagnosticMessage; - A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: DiagnosticMessage; - Duplicate_label_0: DiagnosticMessage; - A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: DiagnosticMessage; - A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: DiagnosticMessage; - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: DiagnosticMessage; - An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: DiagnosticMessage; - An_object_literal_cannot_have_property_and_accessor_with_the_same_name: DiagnosticMessage; - An_export_assignment_cannot_have_modifiers: DiagnosticMessage; - Octal_literals_are_not_allowed_in_strict_mode: DiagnosticMessage; - Variable_declaration_list_cannot_be_empty: DiagnosticMessage; - Digit_expected: DiagnosticMessage; - Hexadecimal_digit_expected: DiagnosticMessage; - Unexpected_end_of_text: DiagnosticMessage; - Invalid_character: DiagnosticMessage; - Declaration_or_statement_expected: DiagnosticMessage; - Statement_expected: DiagnosticMessage; - case_or_default_expected: DiagnosticMessage; - Property_or_signature_expected: DiagnosticMessage; - Enum_member_expected: DiagnosticMessage; - Variable_declaration_expected: DiagnosticMessage; - Argument_expression_expected: DiagnosticMessage; - Property_assignment_expected: DiagnosticMessage; - Expression_or_comma_expected: DiagnosticMessage; - Parameter_declaration_expected: DiagnosticMessage; - Type_parameter_declaration_expected: DiagnosticMessage; - Type_argument_expected: DiagnosticMessage; - String_literal_expected: DiagnosticMessage; - Line_break_not_permitted_here: DiagnosticMessage; - or_expected: DiagnosticMessage; - Declaration_expected: DiagnosticMessage; - Import_declarations_in_a_namespace_cannot_reference_a_module: DiagnosticMessage; - Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: DiagnosticMessage; - File_name_0_differs_from_already_included_file_name_1_only_in_casing: DiagnosticMessage; - new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: DiagnosticMessage; - const_declarations_must_be_initialized: DiagnosticMessage; - const_declarations_can_only_be_declared_inside_a_block: DiagnosticMessage; - let_declarations_can_only_be_declared_inside_a_block: DiagnosticMessage; - Unterminated_template_literal: DiagnosticMessage; - Unterminated_regular_expression_literal: DiagnosticMessage; - An_object_member_cannot_be_declared_optional: DiagnosticMessage; - A_yield_expression_is_only_allowed_in_a_generator_body: DiagnosticMessage; - Computed_property_names_are_not_allowed_in_enums: DiagnosticMessage; - A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: DiagnosticMessage; - A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: DiagnosticMessage; - A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: DiagnosticMessage; - A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: DiagnosticMessage; - A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: DiagnosticMessage; - A_comma_expression_is_not_allowed_in_a_computed_property_name: DiagnosticMessage; - extends_clause_already_seen: DiagnosticMessage; - extends_clause_must_precede_implements_clause: DiagnosticMessage; - Classes_can_only_extend_a_single_class: DiagnosticMessage; - implements_clause_already_seen: DiagnosticMessage; - Interface_declaration_cannot_have_implements_clause: DiagnosticMessage; - Binary_digit_expected: DiagnosticMessage; - Octal_digit_expected: DiagnosticMessage; - Unexpected_token_expected: DiagnosticMessage; - Property_destructuring_pattern_expected: DiagnosticMessage; - Array_element_destructuring_pattern_expected: DiagnosticMessage; - A_destructuring_declaration_must_have_an_initializer: DiagnosticMessage; - An_implementation_cannot_be_declared_in_ambient_contexts: DiagnosticMessage; - Modifiers_cannot_appear_here: DiagnosticMessage; - Merge_conflict_marker_encountered: DiagnosticMessage; - A_rest_element_cannot_have_an_initializer: DiagnosticMessage; - A_parameter_property_may_not_be_declared_using_a_binding_pattern: DiagnosticMessage; - Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: DiagnosticMessage; - The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: DiagnosticMessage; - The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: DiagnosticMessage; - An_import_declaration_cannot_have_modifiers: DiagnosticMessage; - Module_0_has_no_default_export: DiagnosticMessage; - An_export_declaration_cannot_have_modifiers: DiagnosticMessage; - Export_declarations_are_not_permitted_in_a_namespace: DiagnosticMessage; - Catch_clause_variable_cannot_have_a_type_annotation: DiagnosticMessage; - Catch_clause_variable_cannot_have_an_initializer: DiagnosticMessage; - An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: DiagnosticMessage; - Unterminated_Unicode_escape_sequence: DiagnosticMessage; - Line_terminator_not_permitted_before_arrow: DiagnosticMessage; - 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: DiagnosticMessage; - Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: DiagnosticMessage; - Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: DiagnosticMessage; - Decorators_are_not_valid_here: DiagnosticMessage; - Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: DiagnosticMessage; - Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: DiagnosticMessage; - Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: DiagnosticMessage; - Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: DiagnosticMessage; - A_class_declaration_without_the_default_modifier_must_have_a_name: DiagnosticMessage; - Identifier_expected_0_is_a_reserved_word_in_strict_mode: DiagnosticMessage; - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: DiagnosticMessage; - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: DiagnosticMessage; - Invalid_use_of_0_Modules_are_automatically_in_strict_mode: DiagnosticMessage; - Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: DiagnosticMessage; - Export_assignment_is_not_supported_when_module_flag_is_system: DiagnosticMessage; - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: DiagnosticMessage; - Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: DiagnosticMessage; - Generators_are_not_allowed_in_an_ambient_context: DiagnosticMessage; - An_overload_signature_cannot_be_declared_as_a_generator: DiagnosticMessage; - _0_tag_already_specified: DiagnosticMessage; - Signature_0_must_be_a_type_predicate: DiagnosticMessage; - Cannot_find_parameter_0: DiagnosticMessage; - Type_predicate_0_is_not_assignable_to_1: DiagnosticMessage; - Parameter_0_is_not_in_the_same_position_as_parameter_1: DiagnosticMessage; - A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: DiagnosticMessage; - A_type_predicate_cannot_reference_a_rest_parameter: DiagnosticMessage; - A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: DiagnosticMessage; - An_export_assignment_can_only_be_used_in_a_module: DiagnosticMessage; - An_import_declaration_can_only_be_used_in_a_namespace_or_module: DiagnosticMessage; - An_export_declaration_can_only_be_used_in_a_module: DiagnosticMessage; - An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: DiagnosticMessage; - A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: DiagnosticMessage; - The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: DiagnosticMessage; - The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: DiagnosticMessage; - Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: DiagnosticMessage; - Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: DiagnosticMessage; - Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: DiagnosticMessage; - Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: DiagnosticMessage; - abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: DiagnosticMessage; - _0_modifier_cannot_be_used_with_1_modifier: DiagnosticMessage; - Abstract_methods_can_only_appear_within_an_abstract_class: DiagnosticMessage; - Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: DiagnosticMessage; - An_interface_property_cannot_have_an_initializer: DiagnosticMessage; - A_type_literal_property_cannot_have_an_initializer: DiagnosticMessage; - A_class_member_cannot_have_the_0_keyword: DiagnosticMessage; - A_decorator_can_only_decorate_a_method_implementation_not_an_overload: DiagnosticMessage; - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: DiagnosticMessage; - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: DiagnosticMessage; - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: DiagnosticMessage; - _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: DiagnosticMessage; - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: DiagnosticMessage; - A_definite_assignment_assertion_is_not_permitted_in_this_context: DiagnosticMessage; - A_rest_element_must_be_last_in_a_tuple_type: DiagnosticMessage; - A_required_element_cannot_follow_an_optional_element: DiagnosticMessage; - with_statements_are_not_allowed_in_an_async_function_block: DiagnosticMessage; - await_expression_is_only_allowed_within_an_async_function: DiagnosticMessage; - can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: DiagnosticMessage; - The_body_of_an_if_statement_cannot_be_the_empty_statement: DiagnosticMessage; - Global_module_exports_may_only_appear_in_module_files: DiagnosticMessage; - Global_module_exports_may_only_appear_in_declaration_files: DiagnosticMessage; - Global_module_exports_may_only_appear_at_top_level: DiagnosticMessage; - A_parameter_property_cannot_be_declared_using_a_rest_parameter: DiagnosticMessage; - An_abstract_accessor_cannot_have_an_implementation: DiagnosticMessage; - A_default_export_can_only_be_used_in_an_ECMAScript_style_module: DiagnosticMessage; - Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: DiagnosticMessage; - Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: DiagnosticMessage; - Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: DiagnosticMessage; - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: DiagnosticMessage; - Dynamic_import_must_have_one_specifier_as_an_argument: DiagnosticMessage; - Specifier_of_dynamic_import_cannot_be_spread_element: DiagnosticMessage; - Dynamic_import_cannot_have_type_arguments: DiagnosticMessage; - String_literal_with_double_quotes_expected: DiagnosticMessage; - Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: DiagnosticMessage; - _0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0: DiagnosticMessage; - A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly: DiagnosticMessage; - A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly: DiagnosticMessage; - A_variable_whose_type_is_a_unique_symbol_type_must_be_const: DiagnosticMessage; - unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: DiagnosticMessage; - unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: DiagnosticMessage; - unique_symbol_types_are_not_allowed_here: DiagnosticMessage; - An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: DiagnosticMessage; - An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: DiagnosticMessage; - infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: DiagnosticMessage; - Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: DiagnosticMessage; - Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: DiagnosticMessage; - Type_arguments_cannot_be_used_here: DiagnosticMessage; - The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: DiagnosticMessage; - Duplicate_identifier_0: DiagnosticMessage; - Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: DiagnosticMessage; - Static_members_cannot_reference_class_type_parameters: DiagnosticMessage; - Circular_definition_of_import_alias_0: DiagnosticMessage; - Cannot_find_name_0: DiagnosticMessage; - Module_0_has_no_exported_member_1: DiagnosticMessage; - File_0_is_not_a_module: DiagnosticMessage; - Cannot_find_module_0: DiagnosticMessage; - Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: DiagnosticMessage; - An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: DiagnosticMessage; - Type_0_recursively_references_itself_as_a_base_type: DiagnosticMessage; - A_class_may_only_extend_another_class: DiagnosticMessage; - An_interface_may_only_extend_a_class_or_another_interface: DiagnosticMessage; - Type_parameter_0_has_a_circular_constraint: DiagnosticMessage; - Generic_type_0_requires_1_type_argument_s: DiagnosticMessage; - Type_0_is_not_generic: DiagnosticMessage; - Global_type_0_must_be_a_class_or_interface_type: DiagnosticMessage; - Global_type_0_must_have_1_type_parameter_s: DiagnosticMessage; - Cannot_find_global_type_0: DiagnosticMessage; - Named_property_0_of_types_1_and_2_are_not_identical: DiagnosticMessage; - Interface_0_cannot_simultaneously_extend_types_1_and_2: DiagnosticMessage; - Excessive_stack_depth_comparing_types_0_and_1: DiagnosticMessage; - Type_0_is_not_assignable_to_type_1: DiagnosticMessage; - Cannot_redeclare_exported_variable_0: DiagnosticMessage; - Property_0_is_missing_in_type_1: DiagnosticMessage; - Property_0_is_private_in_type_1_but_not_in_type_2: DiagnosticMessage; - Types_of_property_0_are_incompatible: DiagnosticMessage; - Property_0_is_optional_in_type_1_but_required_in_type_2: DiagnosticMessage; - Types_of_parameters_0_and_1_are_incompatible: DiagnosticMessage; - Index_signature_is_missing_in_type_0: DiagnosticMessage; - Index_signatures_are_incompatible: DiagnosticMessage; - this_cannot_be_referenced_in_a_module_or_namespace_body: DiagnosticMessage; - this_cannot_be_referenced_in_current_location: DiagnosticMessage; - this_cannot_be_referenced_in_constructor_arguments: DiagnosticMessage; - this_cannot_be_referenced_in_a_static_property_initializer: DiagnosticMessage; - super_can_only_be_referenced_in_a_derived_class: DiagnosticMessage; - super_cannot_be_referenced_in_constructor_arguments: DiagnosticMessage; - Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: DiagnosticMessage; - super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: DiagnosticMessage; - Property_0_does_not_exist_on_type_1: DiagnosticMessage; - Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: DiagnosticMessage; - Property_0_is_private_and_only_accessible_within_class_1: DiagnosticMessage; - An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: DiagnosticMessage; - This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: DiagnosticMessage; - Type_0_does_not_satisfy_the_constraint_1: DiagnosticMessage; - Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: DiagnosticMessage; - Call_target_does_not_contain_any_signatures: DiagnosticMessage; - Untyped_function_calls_may_not_accept_type_arguments: DiagnosticMessage; - Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: DiagnosticMessage; - Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: DiagnosticMessage; - Only_a_void_function_can_be_called_with_the_new_keyword: DiagnosticMessage; - Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: DiagnosticMessage; - Type_0_cannot_be_converted_to_type_1: DiagnosticMessage; - Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: DiagnosticMessage; - This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: DiagnosticMessage; - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: DiagnosticMessage; - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: DiagnosticMessage; - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: DiagnosticMessage; - The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: DiagnosticMessage; - The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: DiagnosticMessage; - The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: DiagnosticMessage; - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: DiagnosticMessage; - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: DiagnosticMessage; - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: DiagnosticMessage; - The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: DiagnosticMessage; - Operator_0_cannot_be_applied_to_types_1_and_2: DiagnosticMessage; - Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: DiagnosticMessage; - This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: DiagnosticMessage; - Type_parameter_name_cannot_be_0: DiagnosticMessage; - A_parameter_property_is_only_allowed_in_a_constructor_implementation: DiagnosticMessage; - A_rest_parameter_must_be_of_an_array_type: DiagnosticMessage; - A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: DiagnosticMessage; - Parameter_0_cannot_be_referenced_in_its_initializer: DiagnosticMessage; - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: DiagnosticMessage; - Duplicate_string_index_signature: DiagnosticMessage; - Duplicate_number_index_signature: DiagnosticMessage; - A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: DiagnosticMessage; - Constructors_for_derived_classes_must_contain_a_super_call: DiagnosticMessage; - A_get_accessor_must_return_a_value: DiagnosticMessage; - Getter_and_setter_accessors_do_not_agree_in_visibility: DiagnosticMessage; - get_and_set_accessor_must_have_the_same_type: DiagnosticMessage; - A_signature_with_an_implementation_cannot_use_a_string_literal_type: DiagnosticMessage; - Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: DiagnosticMessage; - Overload_signatures_must_all_be_exported_or_non_exported: DiagnosticMessage; - Overload_signatures_must_all_be_ambient_or_non_ambient: DiagnosticMessage; - Overload_signatures_must_all_be_public_private_or_protected: DiagnosticMessage; - Overload_signatures_must_all_be_optional_or_required: DiagnosticMessage; - Function_overload_must_be_static: DiagnosticMessage; - Function_overload_must_not_be_static: DiagnosticMessage; - Function_implementation_name_must_be_0: DiagnosticMessage; - Constructor_implementation_is_missing: DiagnosticMessage; - Function_implementation_is_missing_or_not_immediately_following_the_declaration: DiagnosticMessage; - Multiple_constructor_implementations_are_not_allowed: DiagnosticMessage; - Duplicate_function_implementation: DiagnosticMessage; - Overload_signature_is_not_compatible_with_function_implementation: DiagnosticMessage; - Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: DiagnosticMessage; - Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: DiagnosticMessage; - Declaration_name_conflicts_with_built_in_global_identifier_0: DiagnosticMessage; - Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: DiagnosticMessage; - Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: DiagnosticMessage; - Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: DiagnosticMessage; - Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: DiagnosticMessage; - Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: DiagnosticMessage; - The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: DiagnosticMessage; - The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: DiagnosticMessage; - The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: DiagnosticMessage; - The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: DiagnosticMessage; - Setters_cannot_return_a_value: DiagnosticMessage; - Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: DiagnosticMessage; - The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: DiagnosticMessage; - Property_0_of_type_1_is_not_assignable_to_string_index_type_2: DiagnosticMessage; - Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: DiagnosticMessage; - Numeric_index_type_0_is_not_assignable_to_string_index_type_1: DiagnosticMessage; - Class_name_cannot_be_0: DiagnosticMessage; - Class_0_incorrectly_extends_base_class_1: DiagnosticMessage; - Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: DiagnosticMessage; - Class_static_side_0_incorrectly_extends_base_class_static_side_1: DiagnosticMessage; - Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: DiagnosticMessage; - Class_0_incorrectly_implements_interface_1: DiagnosticMessage; - A_class_may_only_implement_another_class_or_interface: DiagnosticMessage; - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: DiagnosticMessage; - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: DiagnosticMessage; - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: DiagnosticMessage; - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: DiagnosticMessage; - Interface_name_cannot_be_0: DiagnosticMessage; - All_declarations_of_0_must_have_identical_type_parameters: DiagnosticMessage; - Interface_0_incorrectly_extends_interface_1: DiagnosticMessage; - Enum_name_cannot_be_0: DiagnosticMessage; - In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: DiagnosticMessage; - A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: DiagnosticMessage; - A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: DiagnosticMessage; - Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: DiagnosticMessage; - Ambient_module_declaration_cannot_specify_relative_module_name: DiagnosticMessage; - Module_0_is_hidden_by_a_local_declaration_with_the_same_name: DiagnosticMessage; - Import_name_cannot_be_0: DiagnosticMessage; - Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: DiagnosticMessage; - Import_declaration_conflicts_with_local_declaration_of_0: DiagnosticMessage; - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: DiagnosticMessage; - Types_have_separate_declarations_of_a_private_property_0: DiagnosticMessage; - Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: DiagnosticMessage; - Property_0_is_protected_in_type_1_but_public_in_type_2: DiagnosticMessage; - Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: DiagnosticMessage; - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: DiagnosticMessage; - The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: DiagnosticMessage; - Block_scoped_variable_0_used_before_its_declaration: DiagnosticMessage; - Class_0_used_before_its_declaration: DiagnosticMessage; - Enum_0_used_before_its_declaration: DiagnosticMessage; - Cannot_redeclare_block_scoped_variable_0: DiagnosticMessage; - An_enum_member_cannot_have_a_numeric_name: DiagnosticMessage; - The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: DiagnosticMessage; - Variable_0_is_used_before_being_assigned: DiagnosticMessage; - Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: DiagnosticMessage; - Type_alias_0_circularly_references_itself: DiagnosticMessage; - Type_alias_name_cannot_be_0: DiagnosticMessage; - An_AMD_module_cannot_have_multiple_name_assignments: DiagnosticMessage; - Type_0_has_no_property_1_and_no_string_index_signature: DiagnosticMessage; - Type_0_has_no_property_1: DiagnosticMessage; - Type_0_is_not_an_array_type: DiagnosticMessage; - A_rest_element_must_be_last_in_a_destructuring_pattern: DiagnosticMessage; - A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: DiagnosticMessage; - A_computed_property_name_must_be_of_type_string_number_symbol_or_any: DiagnosticMessage; - this_cannot_be_referenced_in_a_computed_property_name: DiagnosticMessage; - super_cannot_be_referenced_in_a_computed_property_name: DiagnosticMessage; - A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: DiagnosticMessage; - Cannot_find_global_value_0: DiagnosticMessage; - The_0_operator_cannot_be_applied_to_type_symbol: DiagnosticMessage; - Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: DiagnosticMessage; - A_computed_property_name_of_the_form_0_must_be_of_type_symbol: DiagnosticMessage; - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: DiagnosticMessage; - Enum_declarations_must_all_be_const_or_non_const: DiagnosticMessage; - In_const_enum_declarations_member_initializer_must_be_constant_expression: DiagnosticMessage; - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: DiagnosticMessage; - A_const_enum_member_can_only_be_accessed_using_a_string_literal: DiagnosticMessage; - const_enum_member_initializer_was_evaluated_to_a_non_finite_value: DiagnosticMessage; - const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: DiagnosticMessage; - Property_0_does_not_exist_on_const_enum_1: DiagnosticMessage; - let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: DiagnosticMessage; - Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: DiagnosticMessage; - The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: DiagnosticMessage; - Export_declaration_conflicts_with_exported_declaration_of_0: DiagnosticMessage; - The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: DiagnosticMessage; - Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: DiagnosticMessage; - An_iterator_must_have_a_next_method: DiagnosticMessage; - The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: DiagnosticMessage; - The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: DiagnosticMessage; - Cannot_redeclare_identifier_0_in_catch_clause: DiagnosticMessage; - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: DiagnosticMessage; - Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: DiagnosticMessage; - Type_0_is_not_an_array_type_or_a_string_type: DiagnosticMessage; - The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: DiagnosticMessage; - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: DiagnosticMessage; - Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: DiagnosticMessage; - An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: DiagnosticMessage; - A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: DiagnosticMessage; - A_rest_element_cannot_contain_a_binding_pattern: DiagnosticMessage; - _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: DiagnosticMessage; - Cannot_find_namespace_0: DiagnosticMessage; - Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: DiagnosticMessage; - A_generator_cannot_have_a_void_type_annotation: DiagnosticMessage; - _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: DiagnosticMessage; - Type_0_is_not_a_constructor_function_type: DiagnosticMessage; - No_base_constructor_has_the_specified_number_of_type_arguments: DiagnosticMessage; - Base_constructor_return_type_0_is_not_a_class_or_interface_type: DiagnosticMessage; - Base_constructors_must_all_have_the_same_return_type: DiagnosticMessage; - Cannot_create_an_instance_of_an_abstract_class: DiagnosticMessage; - Overload_signatures_must_all_be_abstract_or_non_abstract: DiagnosticMessage; - Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: DiagnosticMessage; - Classes_containing_abstract_methods_must_be_marked_abstract: DiagnosticMessage; - Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: DiagnosticMessage; - All_declarations_of_an_abstract_method_must_be_consecutive: DiagnosticMessage; - Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: DiagnosticMessage; - A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: DiagnosticMessage; - An_async_iterator_must_have_a_next_method: DiagnosticMessage; - Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: DiagnosticMessage; - Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: DiagnosticMessage; - The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: DiagnosticMessage; - yield_expressions_cannot_be_used_in_a_parameter_initializer: DiagnosticMessage; - await_expressions_cannot_be_used_in_a_parameter_initializer: DiagnosticMessage; - Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: DiagnosticMessage; - A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: DiagnosticMessage; - The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: DiagnosticMessage; - A_module_cannot_have_multiple_default_exports: DiagnosticMessage; - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: DiagnosticMessage; - Property_0_is_incompatible_with_index_signature: DiagnosticMessage; - Object_is_possibly_null: DiagnosticMessage; - Object_is_possibly_undefined: DiagnosticMessage; - Object_is_possibly_null_or_undefined: DiagnosticMessage; - A_function_returning_never_cannot_have_a_reachable_end_point: DiagnosticMessage; - Enum_type_0_has_members_with_initializers_that_are_not_literals: DiagnosticMessage; - Type_0_cannot_be_used_to_index_type_1: DiagnosticMessage; - Type_0_has_no_matching_index_signature_for_type_1: DiagnosticMessage; - Type_0_cannot_be_used_as_an_index_type: DiagnosticMessage; - Cannot_assign_to_0_because_it_is_not_a_variable: DiagnosticMessage; - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: DiagnosticMessage; - The_target_of_an_assignment_must_be_a_variable_or_a_property_access: DiagnosticMessage; - Index_signature_in_type_0_only_permits_reading: DiagnosticMessage; - Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: DiagnosticMessage; - Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: DiagnosticMessage; - A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: DiagnosticMessage; - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: DiagnosticMessage; - The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: DiagnosticMessage; - Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: DiagnosticMessage; - Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: DiagnosticMessage; - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: DiagnosticMessage; - Property_0_does_not_exist_on_type_1_Did_you_mean_2: DiagnosticMessage; - Cannot_find_name_0_Did_you_mean_1: DiagnosticMessage; - Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: DiagnosticMessage; - Expected_0_arguments_but_got_1: DiagnosticMessage; - Expected_at_least_0_arguments_but_got_1: DiagnosticMessage; - Expected_0_arguments_but_got_1_or_more: DiagnosticMessage; - Expected_at_least_0_arguments_but_got_1_or_more: DiagnosticMessage; - Expected_0_type_arguments_but_got_1: DiagnosticMessage; - Type_0_has_no_properties_in_common_with_type_1: DiagnosticMessage; - Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: DiagnosticMessage; - Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: DiagnosticMessage; - Base_class_expressions_cannot_reference_class_type_parameters: DiagnosticMessage; - The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: DiagnosticMessage; - Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: DiagnosticMessage; - Property_0_is_used_before_being_assigned: DiagnosticMessage; - A_rest_element_cannot_have_a_property_name: DiagnosticMessage; - Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: DiagnosticMessage; - Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: DiagnosticMessage; - Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: DiagnosticMessage; - Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: DiagnosticMessage; - Object_is_of_type_unknown: DiagnosticMessage; - Rest_signatures_are_incompatible: DiagnosticMessage; - Property_0_is_incompatible_with_rest_element_type: DiagnosticMessage; - A_rest_element_type_must_be_an_array_type: DiagnosticMessage; - JSX_element_attributes_type_0_may_not_be_a_union_type: DiagnosticMessage; - The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: DiagnosticMessage; - JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: DiagnosticMessage; - Property_0_in_type_1_is_not_assignable_to_type_2: DiagnosticMessage; - JSX_element_type_0_does_not_have_any_construct_or_call_signatures: DiagnosticMessage; - JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: DiagnosticMessage; - Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: DiagnosticMessage; - JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: DiagnosticMessage; - The_global_type_JSX_0_may_not_have_more_than_one_property: DiagnosticMessage; - JSX_spread_child_must_be_an_array_type: DiagnosticMessage; - Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: DiagnosticMessage; - A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: DiagnosticMessage; - Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: DiagnosticMessage; - Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: DiagnosticMessage; - Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: DiagnosticMessage; - Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: DiagnosticMessage; - JSX_expressions_must_have_one_parent_element: DiagnosticMessage; - Type_0_provides_no_match_for_the_signature_1: DiagnosticMessage; - super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: DiagnosticMessage; - super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: DiagnosticMessage; - Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: DiagnosticMessage; - Cannot_find_name_0_Did_you_mean_the_static_member_1_0: DiagnosticMessage; - Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: DiagnosticMessage; - Invalid_module_name_in_augmentation_module_0_cannot_be_found: DiagnosticMessage; - Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: DiagnosticMessage; - Exports_and_export_assignments_are_not_permitted_in_module_augmentations: DiagnosticMessage; - Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: DiagnosticMessage; - export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: DiagnosticMessage; - Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: DiagnosticMessage; - Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: DiagnosticMessage; - Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: DiagnosticMessage; - Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: DiagnosticMessage; - Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: DiagnosticMessage; - Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: DiagnosticMessage; - Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: DiagnosticMessage; - Accessors_must_both_be_abstract_or_non_abstract: DiagnosticMessage; - A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: DiagnosticMessage; - Type_0_is_not_comparable_to_type_1: DiagnosticMessage; - A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: DiagnosticMessage; - A_0_parameter_must_be_the_first_parameter: DiagnosticMessage; - A_constructor_cannot_have_a_this_parameter: DiagnosticMessage; - get_and_set_accessor_must_have_the_same_this_type: DiagnosticMessage; - this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: DiagnosticMessage; - The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: DiagnosticMessage; - The_this_types_of_each_signature_are_incompatible: DiagnosticMessage; - _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: DiagnosticMessage; - All_declarations_of_0_must_have_identical_modifiers: DiagnosticMessage; - Cannot_find_type_definition_file_for_0: DiagnosticMessage; - Cannot_extend_an_interface_0_Did_you_mean_implements: DiagnosticMessage; - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: DiagnosticMessage; - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: DiagnosticMessage; - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: DiagnosticMessage; - Namespace_0_has_no_exported_member_1: DiagnosticMessage; - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: DiagnosticMessage; - The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: DiagnosticMessage; - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: DiagnosticMessage; - Spread_types_may_only_be_created_from_object_types: DiagnosticMessage; - Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: DiagnosticMessage; - Rest_types_may_only_be_created_from_object_types: DiagnosticMessage; - The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: DiagnosticMessage; - _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: DiagnosticMessage; - The_operand_of_a_delete_operator_must_be_a_property_reference: DiagnosticMessage; - The_operand_of_a_delete_operator_cannot_be_a_read_only_property: DiagnosticMessage; - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: DiagnosticMessage; - Required_type_parameters_may_not_follow_optional_type_parameters: DiagnosticMessage; - Generic_type_0_requires_between_1_and_2_type_arguments: DiagnosticMessage; - Cannot_use_namespace_0_as_a_value: DiagnosticMessage; - Cannot_use_namespace_0_as_a_type: DiagnosticMessage; - _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: DiagnosticMessage; - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: DiagnosticMessage; - 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: DiagnosticMessage; - 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: DiagnosticMessage; - The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: DiagnosticMessage; - Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: DiagnosticMessage; - Type_parameter_0_has_a_circular_default: DiagnosticMessage; - Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: DiagnosticMessage; - Duplicate_declaration_0: DiagnosticMessage; - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: DiagnosticMessage; - Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: DiagnosticMessage; - Cannot_invoke_an_object_which_is_possibly_null: DiagnosticMessage; - Cannot_invoke_an_object_which_is_possibly_undefined: DiagnosticMessage; - Cannot_invoke_an_object_which_is_possibly_null_or_undefined: DiagnosticMessage; - Module_0_has_no_exported_member_1_Did_you_mean_2: DiagnosticMessage; - Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: DiagnosticMessage; - Cannot_find_lib_definition_for_0: DiagnosticMessage; - Cannot_find_lib_definition_for_0_Did_you_mean_1: DiagnosticMessage; - _0_was_declared_here: DiagnosticMessage; - Property_0_is_used_before_its_initialization: DiagnosticMessage; - Import_declaration_0_is_using_private_name_1: DiagnosticMessage; - Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: DiagnosticMessage; - Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: DiagnosticMessage; - extends_clause_of_exported_class_0_has_or_is_using_private_name_1: DiagnosticMessage; - extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: DiagnosticMessage; - Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Exported_variable_0_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Exported_variable_0_has_or_is_using_private_name_1: DiagnosticMessage; - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Public_property_0_of_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Property_0_of_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: DiagnosticMessage; - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: DiagnosticMessage; - Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: DiagnosticMessage; - Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: DiagnosticMessage; - Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: DiagnosticMessage; - Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: DiagnosticMessage; - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: DiagnosticMessage; - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: DiagnosticMessage; - Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: DiagnosticMessage; - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: DiagnosticMessage; - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: DiagnosticMessage; - Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: DiagnosticMessage; - Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: DiagnosticMessage; - Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: DiagnosticMessage; - Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: DiagnosticMessage; - Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: DiagnosticMessage; - Return_type_of_exported_function_has_or_is_using_private_name_0: DiagnosticMessage; - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_0_of_exported_function_has_or_is_using_private_name_1: DiagnosticMessage; - Exported_type_alias_0_has_or_is_using_private_name_1: DiagnosticMessage; - Default_export_of_the_module_has_or_is_using_private_name_0: DiagnosticMessage; - Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: DiagnosticMessage; - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: DiagnosticMessage; - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - Property_0_of_exported_class_expression_may_not_be_private_or_protected: DiagnosticMessage; - Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: DiagnosticMessage; - Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Public_method_0_of_exported_class_has_or_is_using_private_name_1: DiagnosticMessage; - Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: DiagnosticMessage; - Method_0_of_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage; - The_current_host_does_not_support_the_0_option: DiagnosticMessage; - Cannot_find_the_common_subdirectory_path_for_the_input_files: DiagnosticMessage; - File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: DiagnosticMessage; - Cannot_read_file_0_Colon_1: DiagnosticMessage; - Failed_to_parse_file_0_Colon_1: DiagnosticMessage; - Unknown_compiler_option_0: DiagnosticMessage; - Compiler_option_0_requires_a_value_of_type_1: DiagnosticMessage; - Could_not_write_file_0_Colon_1: DiagnosticMessage; - Option_project_cannot_be_mixed_with_source_files_on_a_command_line: DiagnosticMessage; - Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: DiagnosticMessage; - Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: DiagnosticMessage; - Option_0_cannot_be_specified_without_specifying_option_1: DiagnosticMessage; - Option_0_cannot_be_specified_with_option_1: DiagnosticMessage; - A_tsconfig_json_file_is_already_defined_at_Colon_0: DiagnosticMessage; - Cannot_write_file_0_because_it_would_overwrite_input_file: DiagnosticMessage; - Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: DiagnosticMessage; - Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: DiagnosticMessage; - The_specified_path_does_not_exist_Colon_0: DiagnosticMessage; - Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: DiagnosticMessage; - Option_paths_cannot_be_used_without_specifying_baseUrl_option: DiagnosticMessage; - Pattern_0_can_have_at_most_one_Asterisk_character: DiagnosticMessage; - Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: DiagnosticMessage; - Substitutions_for_pattern_0_should_be_an_array: DiagnosticMessage; - Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: DiagnosticMessage; - File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: DiagnosticMessage; - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: DiagnosticMessage; - Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: DiagnosticMessage; - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: DiagnosticMessage; - Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: DiagnosticMessage; - Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: DiagnosticMessage; - Generates_a_sourcemap_for_each_corresponding_d_ts_file: DiagnosticMessage; - Concatenate_and_emit_output_to_single_file: DiagnosticMessage; - Generates_corresponding_d_ts_file: DiagnosticMessage; - Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: DiagnosticMessage; - Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: DiagnosticMessage; - Watch_input_files: DiagnosticMessage; - Redirect_output_structure_to_the_directory: DiagnosticMessage; - Do_not_erase_const_enum_declarations_in_generated_code: DiagnosticMessage; - Do_not_emit_outputs_if_any_errors_were_reported: DiagnosticMessage; - Do_not_emit_comments_to_output: DiagnosticMessage; - Do_not_emit_outputs: DiagnosticMessage; - Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: DiagnosticMessage; - Skip_type_checking_of_declaration_files: DiagnosticMessage; - Do_not_resolve_the_real_path_of_symlinks: DiagnosticMessage; - Only_emit_d_ts_declaration_files: DiagnosticMessage; - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: DiagnosticMessage; - Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: DiagnosticMessage; - Print_this_message: DiagnosticMessage; - Print_the_compiler_s_version: DiagnosticMessage; - Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: DiagnosticMessage; - Syntax_Colon_0: DiagnosticMessage; - options: DiagnosticMessage; - file: DiagnosticMessage; - Examples_Colon_0: DiagnosticMessage; - Options_Colon: DiagnosticMessage; - Version_0: DiagnosticMessage; - Insert_command_line_options_and_files_from_a_file: DiagnosticMessage; - Starting_compilation_in_watch_mode: DiagnosticMessage; - File_change_detected_Starting_incremental_compilation: DiagnosticMessage; - KIND: DiagnosticMessage; - FILE: DiagnosticMessage; - VERSION: DiagnosticMessage; - LOCATION: DiagnosticMessage; - DIRECTORY: DiagnosticMessage; - STRATEGY: DiagnosticMessage; - FILE_OR_DIRECTORY: DiagnosticMessage; - Generates_corresponding_map_file: DiagnosticMessage; - Compiler_option_0_expects_an_argument: DiagnosticMessage; - Unterminated_quoted_string_in_response_file_0: DiagnosticMessage; - Argument_for_0_option_must_be_Colon_1: DiagnosticMessage; - Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: DiagnosticMessage; - Unsupported_locale_0: DiagnosticMessage; - Unable_to_open_file_0: DiagnosticMessage; - Corrupted_locale_file_0: DiagnosticMessage; - Raise_error_on_expressions_and_declarations_with_an_implied_any_type: DiagnosticMessage; - File_0_not_found: DiagnosticMessage; - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: DiagnosticMessage; - Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: DiagnosticMessage; - Do_not_emit_declarations_for_code_that_has_an_internal_annotation: DiagnosticMessage; - Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: DiagnosticMessage; - File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: DiagnosticMessage; - Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: DiagnosticMessage; - NEWLINE: DiagnosticMessage; - Option_0_can_only_be_specified_in_tsconfig_json_file: DiagnosticMessage; - Enables_experimental_support_for_ES7_decorators: DiagnosticMessage; - Enables_experimental_support_for_emitting_type_metadata_for_decorators: DiagnosticMessage; - Enables_experimental_support_for_ES7_async_functions: DiagnosticMessage; - Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: DiagnosticMessage; - Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: DiagnosticMessage; - Successfully_created_a_tsconfig_json_file: DiagnosticMessage; - Suppress_excess_property_checks_for_object_literals: DiagnosticMessage; - Stylize_errors_and_messages_using_color_and_context_experimental: DiagnosticMessage; - Do_not_report_errors_on_unused_labels: DiagnosticMessage; - Report_error_when_not_all_code_paths_in_function_return_a_value: DiagnosticMessage; - Report_errors_for_fallthrough_cases_in_switch_statement: DiagnosticMessage; - Do_not_report_errors_on_unreachable_code: DiagnosticMessage; - Disallow_inconsistently_cased_references_to_the_same_file: DiagnosticMessage; - Specify_library_files_to_be_included_in_the_compilation: DiagnosticMessage; - Specify_JSX_code_generation_Colon_preserve_react_native_or_react: DiagnosticMessage; - File_0_has_an_unsupported_extension_so_skipping_it: DiagnosticMessage; - Only_amd_and_system_modules_are_supported_alongside_0: DiagnosticMessage; - Base_directory_to_resolve_non_absolute_module_names: DiagnosticMessage; - Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: DiagnosticMessage; - Enable_tracing_of_the_name_resolution_process: DiagnosticMessage; - Resolving_module_0_from_1: DiagnosticMessage; - Explicitly_specified_module_resolution_kind_Colon_0: DiagnosticMessage; - Module_resolution_kind_is_not_specified_using_0: DiagnosticMessage; - Module_name_0_was_successfully_resolved_to_1: DiagnosticMessage; - Module_name_0_was_not_resolved: DiagnosticMessage; - paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: DiagnosticMessage; - Module_name_0_matched_pattern_1: DiagnosticMessage; - Trying_substitution_0_candidate_module_location_Colon_1: DiagnosticMessage; - Resolving_module_name_0_relative_to_base_url_1_2: DiagnosticMessage; - Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: DiagnosticMessage; - File_0_does_not_exist: DiagnosticMessage; - File_0_exist_use_it_as_a_name_resolution_result: DiagnosticMessage; - Loading_module_0_from_node_modules_folder_target_file_type_1: DiagnosticMessage; - Found_package_json_at_0: DiagnosticMessage; - package_json_does_not_have_a_0_field: DiagnosticMessage; - package_json_has_0_field_1_that_references_2: DiagnosticMessage; - Allow_javascript_files_to_be_compiled: DiagnosticMessage; - Option_0_should_have_array_of_strings_as_a_value: DiagnosticMessage; - Checking_if_0_is_the_longest_matching_prefix_for_1_2: DiagnosticMessage; - Expected_type_of_0_field_in_package_json_to_be_string_got_1: DiagnosticMessage; - baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: DiagnosticMessage; - rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: DiagnosticMessage; - Longest_matching_prefix_for_0_is_1: DiagnosticMessage; - Loading_0_from_the_root_dir_1_candidate_location_2: DiagnosticMessage; - Trying_other_entries_in_rootDirs: DiagnosticMessage; - Module_resolution_using_rootDirs_has_failed: DiagnosticMessage; - Do_not_emit_use_strict_directives_in_module_output: DiagnosticMessage; - Enable_strict_null_checks: DiagnosticMessage; - Unknown_option_excludes_Did_you_mean_exclude: DiagnosticMessage; - Raise_error_on_this_expressions_with_an_implied_any_type: DiagnosticMessage; - Resolving_type_reference_directive_0_containing_file_1_root_directory_2: DiagnosticMessage; - Resolving_using_primary_search_paths: DiagnosticMessage; - Resolving_from_node_modules_folder: DiagnosticMessage; - Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: DiagnosticMessage; - Type_reference_directive_0_was_not_resolved: DiagnosticMessage; - Resolving_with_primary_search_path_0: DiagnosticMessage; - Root_directory_cannot_be_determined_skipping_primary_search_paths: DiagnosticMessage; - Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: DiagnosticMessage; - Type_declaration_files_to_be_included_in_compilation: DiagnosticMessage; - Looking_up_in_node_modules_folder_initial_location_0: DiagnosticMessage; - Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: DiagnosticMessage; - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: DiagnosticMessage; - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: DiagnosticMessage; - Resolving_real_path_for_0_result_1: DiagnosticMessage; - Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: DiagnosticMessage; - File_name_0_has_a_1_extension_stripping_it: DiagnosticMessage; - _0_is_declared_but_its_value_is_never_read: DiagnosticMessage; - Report_errors_on_unused_locals: DiagnosticMessage; - Report_errors_on_unused_parameters: DiagnosticMessage; - The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: DiagnosticMessage; - Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: DiagnosticMessage; - Property_0_is_declared_but_its_value_is_never_read: DiagnosticMessage; - Import_emit_helpers_from_tslib: DiagnosticMessage; - Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: DiagnosticMessage; - Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: DiagnosticMessage; - Module_0_was_resolved_to_1_but_jsx_is_not_set: DiagnosticMessage; - Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: DiagnosticMessage; - Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: DiagnosticMessage; - Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: DiagnosticMessage; - Resolution_for_module_0_was_found_in_cache_from_location_1: DiagnosticMessage; - Directory_0_does_not_exist_skipping_all_lookups_in_it: DiagnosticMessage; - Show_diagnostic_information: DiagnosticMessage; - Show_verbose_diagnostic_information: DiagnosticMessage; - Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: DiagnosticMessage; - Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: DiagnosticMessage; - Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: DiagnosticMessage; - Print_names_of_generated_files_part_of_the_compilation: DiagnosticMessage; - Print_names_of_files_part_of_the_compilation: DiagnosticMessage; - The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: DiagnosticMessage; - Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: DiagnosticMessage; - Do_not_include_the_default_library_file_lib_d_ts: DiagnosticMessage; - Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: DiagnosticMessage; - Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: DiagnosticMessage; - List_of_folders_to_include_type_definitions_from: DiagnosticMessage; - Disable_size_limitations_on_JavaScript_projects: DiagnosticMessage; - The_character_set_of_the_input_files: DiagnosticMessage; - Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: DiagnosticMessage; - Do_not_truncate_error_messages: DiagnosticMessage; - Output_directory_for_generated_declaration_files: DiagnosticMessage; - A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: DiagnosticMessage; - List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: DiagnosticMessage; - Show_all_compiler_options: DiagnosticMessage; - Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: DiagnosticMessage; - Command_line_Options: DiagnosticMessage; - Basic_Options: DiagnosticMessage; - Strict_Type_Checking_Options: DiagnosticMessage; - Module_Resolution_Options: DiagnosticMessage; - Source_Map_Options: DiagnosticMessage; - Additional_Checks: DiagnosticMessage; - Experimental_Options: DiagnosticMessage; - Advanced_Options: DiagnosticMessage; - Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: DiagnosticMessage; - Enable_all_strict_type_checking_options: DiagnosticMessage; - List_of_language_service_plugins: DiagnosticMessage; - Scoped_package_detected_looking_in_0: DiagnosticMessage; - Reusing_resolution_of_module_0_to_file_1_from_old_program: DiagnosticMessage; - Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: DiagnosticMessage; - Disable_strict_checking_of_generic_signatures_in_function_types: DiagnosticMessage; - Enable_strict_checking_of_function_types: DiagnosticMessage; - Enable_strict_checking_of_property_initialization_in_classes: DiagnosticMessage; - Numeric_separators_are_not_allowed_here: DiagnosticMessage; - Multiple_consecutive_numeric_separators_are_not_permitted: DiagnosticMessage; - Found_package_json_at_0_Package_ID_is_1: DiagnosticMessage; - Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: DiagnosticMessage; - All_imports_in_import_declaration_are_unused: DiagnosticMessage; - Found_1_error_Watching_for_file_changes: DiagnosticMessage; - Found_0_errors_Watching_for_file_changes: DiagnosticMessage; - Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: DiagnosticMessage; - _0_is_declared_but_never_used: DiagnosticMessage; - Include_modules_imported_with_json_extension: DiagnosticMessage; - All_destructured_elements_are_unused: DiagnosticMessage; - All_variables_are_unused: DiagnosticMessage; - Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: DiagnosticMessage; - Conflicts_are_in_this_file: DiagnosticMessage; - _0_was_also_declared_here: DiagnosticMessage; - and_here: DiagnosticMessage; - Projects_to_reference: DiagnosticMessage; - Enable_project_compilation: DiagnosticMessage; - Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: DiagnosticMessage; - Composite_projects_may_not_disable_declaration_emit: DiagnosticMessage; - Output_file_0_has_not_been_built_from_source_file_1: DiagnosticMessage; - Referenced_project_0_must_have_setting_composite_Colon_true: DiagnosticMessage; - File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: DiagnosticMessage; - Cannot_prepend_project_0_because_it_does_not_have_outFile_set: DiagnosticMessage; - Output_file_0_from_project_1_does_not_exist: DiagnosticMessage; - Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: DiagnosticMessage; - Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: DiagnosticMessage; - Project_0_is_out_of_date_because_output_file_1_does_not_exist: DiagnosticMessage; - Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: DiagnosticMessage; - Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: DiagnosticMessage; - Projects_in_this_build_Colon_0: DiagnosticMessage; - A_non_dry_build_would_delete_the_following_files_Colon_0: DiagnosticMessage; - A_non_dry_build_would_build_project_0: DiagnosticMessage; - Building_project_0: DiagnosticMessage; - Updating_output_timestamps_of_project_0: DiagnosticMessage; - delete_this_Project_0_is_up_to_date_because_it_was_previously_built: DiagnosticMessage; - Project_0_is_up_to_date: DiagnosticMessage; - Skipping_build_of_project_0_because_its_dependency_1_has_errors: DiagnosticMessage; - Project_0_can_t_be_built_because_its_dependency_1_has_errors: DiagnosticMessage; - Build_one_or_more_projects_and_their_dependencies_if_out_of_date: DiagnosticMessage; - Delete_the_outputs_of_all_projects: DiagnosticMessage; - Enable_verbose_logging: DiagnosticMessage; - Show_what_would_be_built_or_deleted_if_specified_with_clean: DiagnosticMessage; - Build_all_projects_including_those_that_appear_to_be_up_to_date: DiagnosticMessage; - Option_build_must_be_the_first_command_line_argument: DiagnosticMessage; - Options_0_and_1_cannot_be_combined: DiagnosticMessage; - Skipping_clean_because_not_all_projects_could_be_located: DiagnosticMessage; - The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: DiagnosticMessage; - The_expected_type_comes_from_this_index_signature: DiagnosticMessage; - Variable_0_implicitly_has_an_1_type: DiagnosticMessage; - Parameter_0_implicitly_has_an_1_type: DiagnosticMessage; - Member_0_implicitly_has_an_1_type: DiagnosticMessage; - new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: DiagnosticMessage; - _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: DiagnosticMessage; - Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: DiagnosticMessage; - Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: DiagnosticMessage; - Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: DiagnosticMessage; - Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: DiagnosticMessage; - Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: DiagnosticMessage; - Object_literal_s_property_0_implicitly_has_an_1_type: DiagnosticMessage; - Rest_parameter_0_implicitly_has_an_any_type: DiagnosticMessage; - Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: DiagnosticMessage; - _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: DiagnosticMessage; - _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: DiagnosticMessage; - Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: DiagnosticMessage; - Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: DiagnosticMessage; - JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: DiagnosticMessage; - Unreachable_code_detected: DiagnosticMessage; - Unused_label: DiagnosticMessage; - Fallthrough_case_in_switch: DiagnosticMessage; - Not_all_code_paths_return_a_value: DiagnosticMessage; - Binding_element_0_implicitly_has_an_1_type: DiagnosticMessage; - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: DiagnosticMessage; - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: DiagnosticMessage; - Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: DiagnosticMessage; - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: DiagnosticMessage; - Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: DiagnosticMessage; - Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: DiagnosticMessage; - Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: DiagnosticMessage; - Mapped_object_type_implicitly_has_an_any_template_type: DiagnosticMessage; - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0: DiagnosticMessage; - You_cannot_rename_this_element: DiagnosticMessage; - You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: DiagnosticMessage; - import_can_only_be_used_in_a_ts_file: DiagnosticMessage; - export_can_only_be_used_in_a_ts_file: DiagnosticMessage; - type_parameter_declarations_can_only_be_used_in_a_ts_file: DiagnosticMessage; - implements_clauses_can_only_be_used_in_a_ts_file: DiagnosticMessage; - interface_declarations_can_only_be_used_in_a_ts_file: DiagnosticMessage; - module_declarations_can_only_be_used_in_a_ts_file: DiagnosticMessage; - type_aliases_can_only_be_used_in_a_ts_file: DiagnosticMessage; - _0_can_only_be_used_in_a_ts_file: DiagnosticMessage; - types_can_only_be_used_in_a_ts_file: DiagnosticMessage; - type_arguments_can_only_be_used_in_a_ts_file: DiagnosticMessage; - parameter_modifiers_can_only_be_used_in_a_ts_file: DiagnosticMessage; - non_null_assertions_can_only_be_used_in_a_ts_file: DiagnosticMessage; - enum_declarations_can_only_be_used_in_a_ts_file: DiagnosticMessage; - type_assertion_expressions_can_only_be_used_in_a_ts_file: DiagnosticMessage; - Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: DiagnosticMessage; - Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: DiagnosticMessage; - Report_errors_in_js_files: DiagnosticMessage; - JSDoc_types_can_only_be_used_inside_documentation_comments: DiagnosticMessage; - JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: DiagnosticMessage; - JSDoc_0_is_not_attached_to_a_class: DiagnosticMessage; - JSDoc_0_1_does_not_match_the_extends_2_clause: DiagnosticMessage; - JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: DiagnosticMessage; - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: DiagnosticMessage; - Expected_0_type_arguments_provide_these_with_an_extends_tag: DiagnosticMessage; - Expected_0_1_type_arguments_provide_these_with_an_extends_tag: DiagnosticMessage; - JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: DiagnosticMessage; - JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: DiagnosticMessage; - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: DiagnosticMessage; - class_expressions_are_not_currently_supported: DiagnosticMessage; - Language_service_is_disabled: DiagnosticMessage; - JSX_attributes_must_only_be_assigned_a_non_empty_expression: DiagnosticMessage; - JSX_elements_cannot_have_multiple_attributes_with_the_same_name: DiagnosticMessage; - Expected_corresponding_JSX_closing_tag_for_0: DiagnosticMessage; - JSX_attribute_expected: DiagnosticMessage; - Cannot_use_JSX_unless_the_jsx_flag_is_provided: DiagnosticMessage; - A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: DiagnosticMessage; - An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: DiagnosticMessage; - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: DiagnosticMessage; - JSX_element_0_has_no_corresponding_closing_tag: DiagnosticMessage; - super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: DiagnosticMessage; - Unknown_type_acquisition_option_0: DiagnosticMessage; - super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: DiagnosticMessage; - _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: DiagnosticMessage; - Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: DiagnosticMessage; - JSX_fragment_has_no_corresponding_closing_tag: DiagnosticMessage; - Expected_corresponding_closing_tag_for_JSX_fragment: DiagnosticMessage; - JSX_fragment_is_not_supported_when_using_jsxFactory: DiagnosticMessage; - JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: DiagnosticMessage; - Circularity_detected_while_resolving_configuration_Colon_0: DiagnosticMessage; - A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: DiagnosticMessage; - The_files_list_in_config_file_0_is_empty: DiagnosticMessage; - No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: DiagnosticMessage; - File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: DiagnosticMessage; - This_constructor_function_may_be_converted_to_a_class_declaration: DiagnosticMessage; - Import_may_be_converted_to_a_default_import: DiagnosticMessage; - JSDoc_types_may_be_moved_to_TypeScript_types: DiagnosticMessage; - require_call_may_be_converted_to_an_import: DiagnosticMessage; - Add_missing_super_call: DiagnosticMessage; - Make_super_call_the_first_statement_in_the_constructor: DiagnosticMessage; - Change_extends_to_implements: DiagnosticMessage; - Remove_declaration_for_Colon_0: DiagnosticMessage; - Remove_import_from_0: DiagnosticMessage; - Implement_interface_0: DiagnosticMessage; - Implement_inherited_abstract_class: DiagnosticMessage; - Add_0_to_unresolved_variable: DiagnosticMessage; - Remove_destructuring: DiagnosticMessage; - Remove_variable_statement: DiagnosticMessage; - Import_0_from_module_1: DiagnosticMessage; - Change_0_to_1: DiagnosticMessage; - Add_0_to_existing_import_declaration_from_1: DiagnosticMessage; - Declare_property_0: DiagnosticMessage; - Add_index_signature_for_property_0: DiagnosticMessage; - Disable_checking_for_this_file: DiagnosticMessage; - Ignore_this_error_message: DiagnosticMessage; - Initialize_property_0_in_the_constructor: DiagnosticMessage; - Initialize_static_property_0: DiagnosticMessage; - Change_spelling_to_0: DiagnosticMessage; - Declare_method_0: DiagnosticMessage; - Declare_static_method_0: DiagnosticMessage; - Prefix_0_with_an_underscore: DiagnosticMessage; - Rewrite_as_the_indexed_access_type_0: DiagnosticMessage; - Declare_static_property_0: DiagnosticMessage; - Call_decorator_expression: DiagnosticMessage; - Add_async_modifier_to_containing_function: DiagnosticMessage; - Convert_function_to_an_ES2015_class: DiagnosticMessage; - Convert_function_0_to_class: DiagnosticMessage; - Extract_to_0_in_1: DiagnosticMessage; - Extract_function: DiagnosticMessage; - Extract_constant: DiagnosticMessage; - Extract_to_0_in_enclosing_scope: DiagnosticMessage; - Extract_to_0_in_1_scope: DiagnosticMessage; - Annotate_with_type_from_JSDoc: DiagnosticMessage; - Annotate_with_types_from_JSDoc: DiagnosticMessage; - Infer_type_of_0_from_usage: DiagnosticMessage; - Infer_parameter_types_from_usage: DiagnosticMessage; - Convert_to_default_import: DiagnosticMessage; - Install_0: DiagnosticMessage; - Replace_import_with_0: DiagnosticMessage; - Use_synthetic_default_member: DiagnosticMessage; - Convert_to_ES6_module: DiagnosticMessage; - Add_undefined_type_to_property_0: DiagnosticMessage; - Add_initializer_to_property_0: DiagnosticMessage; - Add_definite_assignment_assertion_to_property_0: DiagnosticMessage; - Add_all_missing_members: DiagnosticMessage; - Infer_all_types_from_usage: DiagnosticMessage; - Delete_all_unused_declarations: DiagnosticMessage; - Prefix_all_unused_declarations_with_where_possible: DiagnosticMessage; - Fix_all_detected_spelling_errors: DiagnosticMessage; - Add_initializers_to_all_uninitialized_properties: DiagnosticMessage; - Add_definite_assignment_assertions_to_all_uninitialized_properties: DiagnosticMessage; - Add_undefined_type_to_all_uninitialized_properties: DiagnosticMessage; - Change_all_jsdoc_style_types_to_TypeScript: DiagnosticMessage; - Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: DiagnosticMessage; - Implement_all_unimplemented_interfaces: DiagnosticMessage; - Install_all_missing_types_packages: DiagnosticMessage; - Rewrite_all_as_indexed_access_types: DiagnosticMessage; - Convert_all_to_default_imports: DiagnosticMessage; - Make_all_super_calls_the_first_statement_in_their_constructor: DiagnosticMessage; - Add_qualifier_to_all_unresolved_variables_matching_a_member_name: DiagnosticMessage; - Change_all_extended_interfaces_to_implements: DiagnosticMessage; - Add_all_missing_super_calls: DiagnosticMessage; - Implement_all_inherited_abstract_classes: DiagnosticMessage; - Add_all_missing_async_modifiers: DiagnosticMessage; - Add_ts_ignore_to_all_error_messages: DiagnosticMessage; - Annotate_everything_with_types_from_JSDoc: DiagnosticMessage; - Add_to_all_uncalled_decorators: DiagnosticMessage; - Convert_all_constructor_functions_to_classes: DiagnosticMessage; - Generate_get_and_set_accessors: DiagnosticMessage; - Convert_require_to_import: DiagnosticMessage; - Convert_all_require_to_import: DiagnosticMessage; - Move_to_a_new_file: DiagnosticMessage; - Remove_unreachable_code: DiagnosticMessage; - Remove_all_unreachable_code: DiagnosticMessage; - Add_missing_typeof: DiagnosticMessage; - Remove_unused_label: DiagnosticMessage; - Remove_all_unused_labels: DiagnosticMessage; - Convert_0_to_mapped_object_type: DiagnosticMessage; - Convert_namespace_import_to_named_imports: DiagnosticMessage; - Convert_named_imports_to_namespace_import: DiagnosticMessage; - Add_or_remove_braces_in_an_arrow_function: DiagnosticMessage; - Add_braces_to_arrow_function: DiagnosticMessage; - Remove_braces_from_arrow_function: DiagnosticMessage; - Convert_default_export_to_named_export: DiagnosticMessage; - Convert_named_export_to_default_export: DiagnosticMessage; - Add_missing_enum_member_0: DiagnosticMessage; - Add_all_missing_imports: DiagnosticMessage; - }; -} declare namespace ts { type ErrorCallback = (message: DiagnosticMessage, length: number) => void; - function tokenIsIdentifierOrKeyword(token: SyntaxKind): boolean; - function tokenIsIdentifierOrKeywordOrGreaterThan(token: SyntaxKind): boolean; interface Scanner { getStartPos(): number; getToken(): SyntaxKind; @@ -5981,7 +3073,6 @@ declare namespace ts { isIdentifier(): boolean; isReservedWord(): boolean; isUnterminated(): boolean; - getTokenFlags(): TokenFlags; reScanGreaterToken(): SyntaxKind; reScanSlashToken(): SyntaxKind; reScanTemplateToken(): SyntaxKind; @@ -6001,25 +3092,14 @@ declare namespace ts { scanRange(start: number, length: number, callback: () => T): T; tryScan(callback: () => T): T; } - function isUnicodeIdentifierStart(code: number, languageVersion: ScriptTarget | undefined): boolean; function tokenToString(t: SyntaxKind): string | undefined; - function stringToToken(s: string): SyntaxKind | undefined; - function computeLineStarts(text: string): number[]; function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number): number; - function computePositionOfLineAndCharacter(lineStarts: ReadonlyArray, line: number, character: number, debugText?: string): number; - function getLineStarts(sourceFile: SourceFileLike): ReadonlyArray; - /** - * We assume the first line starts at position 0 and 'position' is non-negative. - */ - function computeLineAndCharacterOfPosition(lineStarts: ReadonlyArray, position: number): LineAndCharacter; function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; function isWhiteSpaceLike(ch: number): boolean; /** Does not include line breaks. For that, see isWhiteSpaceLike. */ function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; - function isOctalDigit(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean, stopAtComments?: boolean): number; function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; @@ -6032,7 +3112,6 @@ declare namespace ts { function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; - function isIdentifierText(name: string, languageVersion: ScriptTarget | undefined): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } /** Non-internal stuff goes here */ @@ -6040,625 +3119,11 @@ declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; } -declare namespace ts { - const emptyArray: never[]; - const resolvingEmptyArray: never[]; - const emptyMap: ReadonlyMap; - const emptyUnderscoreEscapedMap: ReadonlyUnderscoreEscapedMap; - const externalHelpersModuleNameText = "tslib"; - function getDeclarationOfKind(symbol: Symbol, kind: T["kind"]): T | undefined; - /** Create a new escaped identifier map. */ - function createUnderscoreEscapedMap(): UnderscoreEscapedMap; - function hasEntries(map: ReadonlyUnderscoreEscapedMap | undefined): map is ReadonlyUnderscoreEscapedMap; - function createSymbolTable(symbols?: ReadonlyArray): SymbolTable; - function toPath(fileName: string, basePath: string | undefined, getCanonicalFileName: (path: string) => string): Path; - function changesAffectModuleResolution(oldOptions: CompilerOptions, newOptions: CompilerOptions): boolean; - /** - * Iterates through the parent chain of a node and performs the callback on each parent until the callback - * returns a truthy value, then returns that value. - * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" - * At that point findAncestor returns undefined. - */ - function findAncestor(node: Node | undefined, callback: (element: Node) => element is T): T | undefined; - function findAncestor(node: Node | undefined, callback: (element: Node) => boolean | "quit"): Node | undefined; - /** - * Calls `callback` for each entry in the map, returning the first truthy result. - * Use `map.forEach` instead for normal iteration. - */ - function forEachEntry(map: ReadonlyUnderscoreEscapedMap, callback: (value: T, key: __String) => U | undefined): U | undefined; - function forEachEntry(map: ReadonlyMap, callback: (value: T, key: string) => U | undefined): U | undefined; - /** `forEachEntry` for just keys. */ - function forEachKey(map: ReadonlyUnderscoreEscapedMap<{}>, callback: (key: __String) => T | undefined): T | undefined; - function forEachKey(map: ReadonlyMap<{}>, callback: (key: string) => T | undefined): T | undefined; - /** Copy entries from `source` to `target`. */ - function copyEntries(source: ReadonlyUnderscoreEscapedMap, target: UnderscoreEscapedMap): void; - function copyEntries(source: ReadonlyMap, target: Map): void; - /** - * Creates a set from the elements of an array. - * - * @param array the array of input elements. - */ - function arrayToSet(array: ReadonlyArray): Map; - function arrayToSet(array: ReadonlyArray, makeKey: (value: T) => string | undefined): Map; - function arrayToSet(array: ReadonlyArray, makeKey: (value: T) => __String | undefined): UnderscoreEscapedMap; - function cloneMap(map: SymbolTable): SymbolTable; - function cloneMap(map: ReadonlyMap): Map; - function cloneMap(map: ReadonlyUnderscoreEscapedMap): UnderscoreEscapedMap; - function usingSingleLineStringWriter(action: (writer: EmitTextWriter) => void): string; - function getFullWidth(node: Node): number; - function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModuleFull | undefined; - function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModuleFull): void; - function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective): void; - function moduleResolutionIsEqualTo(oldResolution: ResolvedModuleFull, newResolution: ResolvedModuleFull): boolean; - function packageIdToString({ name, subModuleName, version }: PackageId): string; - function typeDirectiveIsEqualTo(oldResolution: ResolvedTypeReferenceDirective, newResolution: ResolvedTypeReferenceDirective): boolean; - function hasChangesInResolutions(names: ReadonlyArray, newResolutions: ReadonlyArray, oldResolutions: ReadonlyMap | undefined, comparer: (oldResolution: T, newResolution: T) => boolean): boolean; - function containsParseError(node: Node): boolean; - function getSourceFileOfNode(node: Node): SourceFile; - function getSourceFileOfNode(node: Node | undefined): SourceFile | undefined; - function isStatementWithLocals(node: Node): boolean; - function getStartPositionOfLine(line: number, sourceFile: SourceFileLike): number; - function nodePosToString(node: Node): string; - function getEndLinePosition(line: number, sourceFile: SourceFileLike): number; - /** - * Returns a value indicating whether a name is unique globally or within the current file. - * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`. - */ - function isFileLevelUniqueName(sourceFile: SourceFile, name: string, hasGlobalName?: PrintHandlers["hasGlobalName"]): boolean; - function nodeIsMissing(node: Node | undefined): boolean; - function nodeIsPresent(node: Node | undefined): boolean; - /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - */ - function prependStatements(to: T[], from: ReadonlyArray | undefined): T[] | undefined; - /** - * Determine if the given comment is a triple-slash - * - * @return true if the comment is a triple-slash comment else false - */ - function isRecognizedTripleSlashComment(text: string, commentPos: number, commentEnd: number): boolean; - function isPinnedComment(text: string, start: number): boolean; - function getTokenPosOfNode(node: Node, sourceFile?: SourceFileLike, includeJsDoc?: boolean): number; - function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFileLike): number; - function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia?: boolean): string; - function getTextOfNodeFromSourceText(sourceText: string, node: Node, includeTrivia?: boolean): string; - function getTextOfNode(node: Node, includeTrivia?: boolean): string; - /** - * 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: ReadonlyArray, node: Node): number; - /** - * Gets flags that control emit behavior of a node. - */ - function getEmitFlags(node: Node): EmitFlags; - function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile): string; - function getTextOfConstantValue(value: string | number): string; - function escapeLeadingUnderscores(identifier: string): __String; - function makeIdentifierFromModuleName(moduleName: string): string; - function isBlockOrCatchScoped(declaration: Declaration): boolean; - function isCatchClauseVariableDeclarationOrBindingElement(declaration: Declaration): boolean; - function isAmbientModule(node: Node): node is AmbientModuleDeclaration; - function isModuleWithStringLiteralName(node: Node): node is ModuleDeclaration; - function isNonGlobalAmbientModule(node: Node): node is ModuleDeclaration & { - name: StringLiteral; - }; - /** - * An effective module (namespace) declaration is either - * 1. An actual declaration: namespace X { ... } - * 2. A Javascript declaration, which is: - * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }` - */ - function isEffectiveModuleDeclaration(node: Node): boolean; - /** Given a symbol for a module, checks that it is a shorthand ambient module. */ - function isShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean; - function isBlockScopedContainerTopLevel(node: Node): boolean; - function isGlobalScopeAugmentation(module: ModuleDeclaration): boolean; - function isExternalModuleAugmentation(node: Node): node is AmbientModuleDeclaration; - function isModuleAugmentationExternal(node: AmbientModuleDeclaration): boolean; - function isEffectiveExternalModule(node: SourceFile, compilerOptions: CompilerOptions): boolean; - function isBlockScope(node: Node, parentNode: Node): boolean; - function isDeclarationWithTypeParameters(node: Node): node is DeclarationWithTypeParameters; - function isAnyImportSyntax(node: Node): node is AnyImportSyntax; - function isLateVisibilityPaintedStatement(node: Node): node is LateVisibilityPaintedStatement; - function isAnyImportOrReExport(node: Node): node is AnyImportOrReExport; - function getEnclosingBlockScopeContainer(node: Node): Node; - function declarationNameToString(name: DeclarationName | QualifiedName | undefined): string; - function getNameFromIndexInfo(info: IndexInfo): string | undefined; - function getTextOfPropertyName(name: PropertyName): __String; - function entityNameToString(name: EntityNameOrEntityNameExpression): string; - function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): DiagnosticWithLocation; - function createDiagnosticForNodeArray(sourceFile: SourceFile, nodes: NodeArray, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): Diagnostic; - function createDiagnosticForNodeInSourceFile(sourceFile: SourceFile, node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): DiagnosticWithLocation; - function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain, relatedInformation?: DiagnosticRelatedInformation[]): DiagnosticWithLocation; - function getSpanOfTokenAtPosition(sourceFile: SourceFile, pos: number): TextSpan; - function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpan; - function isExternalOrCommonJsModule(file: SourceFile): boolean; - function isJsonSourceFile(file: SourceFile): file is JsonSourceFile; - function isEnumConst(node: EnumDeclaration): boolean; - function isVarConst(node: VariableDeclaration | VariableDeclarationList): boolean; - function isLet(node: Node): boolean; - function isSuperCall(n: Node): n is SuperCall; - function isImportCall(n: Node): n is ImportCall; - function isLiteralImportTypeNode(n: Node): n is LiteralImportTypeNode; - function isPrologueDirective(node: Node): node is PrologueDirective; - function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile): CommentRange[] | undefined; - function getJSDocCommentRanges(node: Node, text: string): CommentRange[] | undefined; - const fullTripleSlashReferencePathRegEx: RegExp; - const fullTripleSlashAMDReferencePathRegEx: RegExp; - function isPartOfTypeNode(node: Node): boolean; - function isChildOfNodeWithKind(node: Node, kind: SyntaxKind): boolean; - function forEachReturnStatement(body: Block, visitor: (stmt: ReturnStatement) => T): T | undefined; - function forEachYieldExpression(body: Block, visitor: (expr: YieldExpression) => void): void; - /** - * Gets the most likely element type for a TypeNode. This is not an exhaustive test - * as it assumes a rest argument can only be an array type (either T[], or Array). - * - * @param node The type node. - */ - function getRestParameterElementType(node: TypeNode | undefined): TypeNode | undefined; - function getMembersOfDeclaration(node: Declaration): NodeArray | undefined; - function isVariableLike(node: Node): node is VariableLikeDeclaration; - function isVariableLikeOrAccessor(node: Node): node is AccessorDeclaration | VariableLikeDeclaration; - function isVariableDeclarationInVariableStatement(node: VariableDeclaration): boolean; - function isValidESSymbolDeclaration(node: Node): node is VariableDeclaration | PropertyDeclaration | SignatureDeclaration; - function introducesArgumentsExoticObject(node: Node): boolean; - function unwrapInnermostStatementOfLabel(node: LabeledStatement, beforeUnwrapLabelCallback?: (node: LabeledStatement) => void): Statement; - function isFunctionBlock(node: Node): boolean; - function isObjectLiteralMethod(node: Node): node is MethodDeclaration; - function isObjectLiteralOrClassExpressionMethod(node: Node): node is MethodDeclaration; - function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate; - function isThisTypePredicate(predicate: TypePredicate): predicate is ThisTypePredicate; - function getPropertyAssignment(objectLiteral: ObjectLiteralExpression, key: string, key2?: string): ReadonlyArray; - function getTsConfigObjectLiteralExpression(tsConfigSourceFile: TsConfigSourceFile | undefined): ObjectLiteralExpression | undefined; - function getTsConfigPropArrayElementValue(tsConfigSourceFile: TsConfigSourceFile | undefined, propKey: string, elementValue: string): StringLiteral | undefined; - function getTsConfigPropArray(tsConfigSourceFile: TsConfigSourceFile | undefined, propKey: string): ReadonlyArray; - function getContainingFunction(node: Node): SignatureDeclaration | undefined; - function getContainingClass(node: Node): ClassLikeDeclaration | undefined; - function getThisContainer(node: Node, includeArrowFunctions: boolean): Node; - function getNewTargetContainer(node: Node): Node | undefined; - /** - * Given an super call/property node, returns the closest node where - * - a super call/property access is legal in the node and not legal in the parent node the node. - * i.e. super call is legal in constructor but not legal in the class body. - * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) - * - a super call/property is definitely illegal in the container (but might be legal in some subnode) - * i.e. super property access is illegal in function declaration but can be legal in the statement list - */ - function getSuperContainer(node: Node, stopOnFunctions: boolean): Node; - function getImmediatelyInvokedFunctionExpression(func: Node): CallExpression | undefined; - /** - * Determines whether a node is a property or element access expression for `super`. - */ - function isSuperProperty(node: Node): node is SuperProperty; - /** - * Determines whether a node is a property or element access expression for `this`. - */ - function isThisProperty(node: Node): boolean; - function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression | undefined; - function getInvokedExpression(node: CallLikeExpression): Expression; - function nodeCanBeDecorated(node: ClassDeclaration): true; - function nodeCanBeDecorated(node: ClassElement, parent: Node): boolean; - function nodeCanBeDecorated(node: Node, parent: Node, grandparent: Node): boolean; - function nodeIsDecorated(node: ClassDeclaration): boolean; - function nodeIsDecorated(node: ClassElement, parent: Node): boolean; - function nodeIsDecorated(node: Node, parent: Node, grandparent: Node): boolean; - function nodeOrChildIsDecorated(node: ClassDeclaration): boolean; - function nodeOrChildIsDecorated(node: ClassElement, parent: Node): boolean; - function nodeOrChildIsDecorated(node: Node, parent: Node, grandparent: Node): boolean; - function childIsDecorated(node: ClassDeclaration): boolean; - function childIsDecorated(node: Node, parent: Node): boolean; - function isJSXTagName(node: Node): boolean; - function isExpressionNode(node: Node): boolean; - function isInExpressionContext(node: Node): boolean; - function isExternalModuleImportEqualsDeclaration(node: Node): boolean; - function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression; - function isInternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; - function isSourceFileJavaScript(file: SourceFile): boolean; - function isSourceFileNotJavaScript(file: SourceFile): boolean; - function isInJavaScriptFile(node: Node | undefined): boolean; - function isInJsonFile(node: Node | undefined): boolean; - function isInJSDoc(node: Node | undefined): boolean; - function isJSDocIndexSignature(node: TypeReferenceNode | ExpressionWithTypeArguments): boolean | undefined; - /** - * Returns true if the node is a CallExpression to the identifier 'require' with - * exactly one argument (of the form 'require("name")'). - * This function does not test if the node is in a JavaScript file or not. - */ - function isRequireCall(callExpression: Node, checkArgumentIsStringLiteralLike: true): callExpression is RequireOrImportCall & { - expression: Identifier; - arguments: [StringLiteralLike]; - }; - function isRequireCall(callExpression: Node, checkArgumentIsStringLiteralLike: boolean): callExpression is CallExpression; - function isSingleOrDoubleQuote(charCode: number): boolean; - function isStringDoubleQuoted(str: StringLiteralLike, sourceFile: SourceFile): boolean; - function getDeclarationOfJSInitializer(node: Node): Node | undefined; - /** Get the initializer, taking into account defaulted Javascript initializers */ - function getEffectiveInitializer(node: HasExpressionInitializer): Expression | undefined; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node: HasExpressionInitializer): Expression | undefined; - /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). - * We treat the right hand side of assignments with container-like initalizers as declarations. - */ - function getAssignedJavascriptInitializer(node: Node): Expression | undefined; - /** - * Recognized Javascript container-like initializers are: - * 1. (function() {})() -- IIFEs - * 2. function() { } -- Function expressions - * 3. class { } -- Class expressions - * 4. {} -- Empty object literals - * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }` - * - * This function returns the provided initializer, or undefined if it is not valid. - */ - function getJavascriptInitializer(initializer: Node, isPrototypeAssignment: boolean): Expression | undefined; - function isDefaultedJavascriptInitializer(node: BinaryExpression): boolean | undefined; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node: Declaration): DeclarationName | undefined; - function getRightMostAssignedExpression(node: Expression): Expression; - function isExportsIdentifier(node: Node): boolean; - function isModuleExportsPropertyAccessExpression(node: Node): boolean; - function getSpecialPropertyAssignmentKind(expr: BinaryExpression): SpecialPropertyAssignmentKind; - function getSpecialPropertyAccessKind(lhs: PropertyAccessExpression): SpecialPropertyAssignmentKind; - function getInitializerOfBinaryExpression(expr: BinaryExpression): Expression; - function isPrototypePropertyAssignment(node: Node): boolean; - function isSpecialPropertyDeclaration(expr: PropertyAccessExpression): boolean; - function importFromModuleSpecifier(node: StringLiteralLike): AnyValidImportOrReExport; - function tryGetImportFromModuleSpecifier(node: StringLiteralLike): AnyValidImportOrReExport | undefined; - function getExternalModuleName(node: AnyImportOrReExport | ImportTypeNode): Expression | undefined; - function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): ImportEqualsDeclaration | NamespaceImport | undefined; - function isDefaultImport(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean; - function hasQuestionToken(node: Node): boolean; - function isJSDocConstructSignature(node: Node): boolean; - function isJSDocTypeAlias(node: Node): node is JSDocTypedefTag | JSDocCallbackTag; - function isTypeAlias(node: Node): node is JSDocTypedefTag | JSDocCallbackTag | TypeAliasDeclaration; - function getJSDocCommentsAndTags(hostNode: Node): ReadonlyArray; - /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ - function getParameterSymbolFromJSDoc(node: JSDocParameterTag): Symbol | undefined; - function getHostSignatureFromJSDoc(node: Node): SignatureDeclaration | undefined; - function getHostSignatureFromJSDocHost(host: HasJSDoc): SignatureDeclaration | undefined; - function getJSDocHost(node: Node): HasJSDoc; - function getTypeParameterFromJsDoc(node: TypeParameterDeclaration & { - parent: JSDocTemplateTag; - }): TypeParameterDeclaration | undefined; - function hasRestParameter(s: SignatureDeclaration | JSDocSignature): boolean; - function isRestParameter(node: ParameterDeclaration | JSDocParameterTag): boolean; - enum AssignmentKind { - None = 0, - Definite = 1, - Compound = 2 - } - function getAssignmentTargetKind(node: Node): AssignmentKind; - function isAssignmentTarget(node: Node): boolean; - type NodeWithPossibleHoistedDeclaration = Block | VariableStatement | WithStatement | IfStatement | SwitchStatement | CaseBlock | CaseClause | DefaultClause | LabeledStatement | ForStatement | ForInStatement | ForOfStatement | DoStatement | WhileStatement | TryStatement | CatchClause; - /** - * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to - * the same `var` declaration scope as the node's parent. - */ - function isNodeWithPossibleHoistedDeclaration(node: Node): node is NodeWithPossibleHoistedDeclaration; - type ValueSignatureDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; - function isValueSignatureDeclaration(node: Node): node is ValueSignatureDeclaration; - function walkUpParenthesizedTypes(node: Node): Node; - function walkUpParenthesizedExpressions(node: Node): Node; - function skipParentheses(node: Expression): Expression; - function skipParentheses(node: Node): Node; - function isDeleteTarget(node: Node): boolean; - function isNodeDescendantOf(node: Node, ancestor: Node): boolean; - function isDeclarationName(name: Node): boolean; - function isAnyDeclarationName(name: Node): boolean; - function isLiteralComputedPropertyDeclarationName(node: Node): boolean; - function isIdentifierName(node: Identifier): boolean; - function isAliasSymbolDeclaration(node: Node): boolean; - function exportAssignmentIsAlias(node: ExportAssignment | BinaryExpression): boolean; - function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments | undefined; - function getClassExtendsHeritageElement(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments | undefined; - function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration): NodeArray | undefined; - /** Returns the node in an `extends` or `implements` clause of a class or interface. */ - function getAllSuperTypeNodes(node: Node): ReadonlyArray; - function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray | undefined; - function getHeritageClause(clauses: NodeArray | undefined, kind: SyntaxKind): HeritageClause | undefined; - function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference): SourceFile | undefined; - function getAncestor(node: Node | undefined, kind: SyntaxKind): Node | undefined; - function isKeyword(token: SyntaxKind): boolean; - function isContextualKeyword(token: SyntaxKind): boolean; - function isNonContextualKeyword(token: SyntaxKind): boolean; - function isStringANonContextualKeyword(name: string): boolean; - type TriviaKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; - function isTrivia(token: SyntaxKind): token is TriviaKind; - enum FunctionFlags { - Normal = 0, - Generator = 1, - Async = 2, - Invalid = 4, - AsyncGenerator = 3 - } - function getFunctionFlags(node: SignatureDeclaration | undefined): FunctionFlags; - function isAsyncFunction(node: Node): boolean; - function isStringOrNumericLiteral(node: Node): node is StringLiteral | NumericLiteral; - /** - * A declaration has a dynamic name if both of the following are true: - * 1. The declaration has a computed property name - * 2. The computed name is *not* expressed as Symbol., where name - * is a property of the Symbol constructor that denotes a built in - * Symbol. - */ - function hasDynamicName(declaration: Declaration): declaration is DynamicNamedDeclaration; - function isDynamicName(name: DeclarationName): boolean; - /** - * Checks if the expression is of the form: - * Symbol.name - * where Symbol is literally the word "Symbol", and name is any identifierName - */ - function isWellKnownSymbolSyntactically(node: Expression): boolean; - function getPropertyNameForPropertyNameNode(name: DeclarationName): __String | undefined; - type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral; - function isPropertyNameLiteral(node: Node): node is PropertyNameLiteral; - function getTextOfIdentifierOrLiteral(node: PropertyNameLiteral): string; - function getEscapedTextOfIdentifierOrLiteral(node: PropertyNameLiteral): __String; - function getPropertyNameForKnownSymbolName(symbolName: string): __String; - function isKnownSymbol(symbol: Symbol): boolean; - /** - * Includes the word "Symbol" with unicode escapes - */ - function isESSymbolIdentifier(node: Node): boolean; - function isPushOrUnshiftIdentifier(node: Identifier): boolean; - function isParameterDeclaration(node: VariableLikeDeclaration): boolean; - function getRootDeclaration(node: Node): Node; - function nodeStartsNewLexicalEnvironment(node: Node): boolean; - function nodeIsSynthesized(range: TextRange): boolean; - function getOriginalSourceFile(sourceFile: SourceFile): SourceFile; - enum Associativity { - Left = 0, - Right = 1 - } - function getExpressionAssociativity(expression: Expression): Associativity; - function getOperatorAssociativity(kind: SyntaxKind, operator: SyntaxKind, hasArguments?: boolean): Associativity; - function getExpressionPrecedence(expression: Expression): number; - function getOperator(expression: Expression): SyntaxKind; - function getOperatorPrecedence(nodeKind: SyntaxKind, operatorKind: SyntaxKind, hasArguments?: boolean): number; - function getBinaryOperatorPrecedence(kind: SyntaxKind): number; - function createDiagnosticCollection(): DiagnosticCollection; - /** - * 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) - * Note that this doesn't actually wrap the input in double quotes. - */ - function escapeString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote | CharacterCodes.backtick): string; - function isIntrinsicJsxName(name: __String | string): boolean; - function escapeNonAsciiString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote | CharacterCodes.backtick): string; - function getIndentString(level: number): string; - function getIndentSize(): number; - function createTextWriter(newLine: string): EmitTextWriter; - function getResolvedExternalModuleName(host: EmitHost, file: SourceFile, referenceFile?: SourceFile): string; - function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration | ImportTypeNode): string | undefined; - /** - * Resolves a local path to a path which is absolute to the base of the emit - */ - function getExternalModuleNameFromPath(host: EmitHost, fileName: string, referencePath?: string): string; - function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string; - function getDeclarationEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost): string; - interface EmitFileNames { - jsFilePath: string; - sourceMapFilePath: string | undefined; - declarationFilePath: string | undefined; - declarationMapPath: string | undefined; - bundleInfoPath: string | undefined; - } - /** - * Gets the source files that are expected to have an emit output. - * - * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support - * transformations. - * - * @param host An EmitHost. - * @param targetSourceFile An optional target source file to emit. - */ - function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFile): ReadonlyArray; - /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ - function sourceFileMayBeEmitted(sourceFile: SourceFile, options: CompilerOptions, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean): boolean; - function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string; - function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: ReadonlyArray): void; - function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number): number; - function getLineOfLocalPositionFromLineMap(lineMap: ReadonlyArray, pos: number): number; - function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration | undefined; - /** Get the type annotation for the value parameter. */ - function getSetAccessorTypeAnnotationNode(accessor: SetAccessorDeclaration): TypeNode | undefined; - function getThisParameter(signature: SignatureDeclaration | JSDocSignature): ParameterDeclaration | undefined; - function parameterIsThisKeyword(parameter: ParameterDeclaration): boolean; - function isThisIdentifier(node: Node | undefined): boolean; - function identifierIsThisKeyword(id: Identifier): boolean; - function getAllAccessorDeclarations(declarations: NodeArray, accessor: AccessorDeclaration): AllAccessorDeclarations; - /** - * Gets the effective type annotation of a variable, parameter, or property. If the node was - * parsed in a JavaScript file, gets the type annotation from JSDoc. - */ - function getEffectiveTypeAnnotationNode(node: Node): TypeNode | undefined; - function getTypeAnnotationNode(node: Node): TypeNode | undefined; - /** - * Gets the effective return type annotation of a signature. If the node was parsed in a - * JavaScript file, gets the return type annotation from JSDoc. - */ - function getEffectiveReturnTypeNode(node: SignatureDeclaration | JSDocSignature): TypeNode | undefined; - /** - * Gets the effective type parameters. If the node was parsed in a - * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. - */ - function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray; - function getJSDocTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray; - /** - * Gets the effective type annotation of the value parameter of a set accessor. If the node - * was parsed in a JavaScript file, gets the type annotation from JSDoc. - */ - function getEffectiveSetAccessorTypeAnnotationNode(node: SetAccessorDeclaration): TypeNode | undefined; - function emitNewLineBeforeLeadingComments(lineMap: ReadonlyArray, writer: EmitTextWriter, node: TextRange, leadingComments: ReadonlyArray | undefined): void; - function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: ReadonlyArray, writer: EmitTextWriter, pos: number, leadingComments: ReadonlyArray | undefined): void; - function emitNewLineBeforeLeadingCommentOfPosition(lineMap: ReadonlyArray, writer: EmitTextWriter, pos: number, commentPos: number): void; - function emitComments(text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, comments: ReadonlyArray | undefined, leadingSeparator: boolean, trailingSeparator: boolean, newLine: string, writeComment: (text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void): void; - /** - * Detached comment is a comment at the top of file or function body that is separated from - * the next statement by space. - */ - function emitDetachedComments(text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, writeComment: (text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, node: TextRange, newLine: string, removeComments: boolean): { - nodePos: number; - detachedCommentEndPos: number; - } | undefined; - function writeCommentRange(text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string): void; - function hasModifiers(node: Node): boolean; - function hasModifier(node: Node, flags: ModifierFlags): boolean; - function hasStaticModifier(node: Node): boolean; - function hasReadonlyModifier(node: Node): boolean; - function getSelectedModifierFlags(node: Node, flags: ModifierFlags): ModifierFlags; - function getModifierFlags(node: Node): ModifierFlags; - function getModifierFlagsNoCache(node: Node): ModifierFlags; - function modifierToFlag(token: SyntaxKind): ModifierFlags; - function isLogicalOperator(token: SyntaxKind): boolean; - function isAssignmentOperator(token: SyntaxKind): boolean; - /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ - function tryGetClassExtendingExpressionWithTypeArguments(node: Node): ClassLikeDeclaration | undefined; - function isAssignmentExpression(node: Node, excludeCompoundAssignment: true): node is AssignmentExpression; - function isAssignmentExpression(node: Node, excludeCompoundAssignment?: false): node is AssignmentExpression; - function isDestructuringAssignment(node: Node): node is DestructuringAssignment; - function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean; - function isExpressionWithTypeArgumentsInClassImplementsClause(node: Node): node is ExpressionWithTypeArguments; - function isEntityNameExpression(node: Node): node is EntityNameExpression; - function isPropertyAccessEntityNameExpression(node: Node): node is PropertyAccessEntityNameExpression; - function isPrototypeAccess(node: Node): node is PropertyAccessExpression; - function isRightSideOfQualifiedNameOrPropertyAccess(node: Node): boolean; - function isEmptyObjectLiteral(expression: Node): boolean; - function isEmptyArrayLiteral(expression: Node): boolean; - function getLocalSymbolForExportDefault(symbol: Symbol): Symbol | undefined; - /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName: string): string | undefined; - /** - * Converts a string to a base-64 encoded ASCII string. - */ - function convertToBase64(input: string): string; - function base64encode(host: { - base64encode?(input: string): string; - } | undefined, input: string): string; - function base64decode(host: { - base64decode?(input: string): string; - } | undefined, input: string): string; - function getNewLineCharacter(options: CompilerOptions | PrinterOptions, getNewLine?: () => string): string; - function formatSyntaxKind(kind: SyntaxKind | undefined): string; - function formatModifierFlags(flags: ModifierFlags | undefined): string; - function formatTransformFlags(flags: TransformFlags | undefined): string; - function formatEmitFlags(flags: EmitFlags | undefined): string; - function formatSymbolFlags(flags: SymbolFlags | undefined): string; - function formatTypeFlags(flags: TypeFlags | undefined): string; - function formatObjectFlags(flags: ObjectFlags | undefined): string; - /** - * Creates a new TextRange from the provided pos and end. - * - * @param pos The start position. - * @param end The end position. - */ - function createRange(pos: number, end: number): TextRange; - /** - * Creates a new TextRange from a provided range with a new end position. - * - * @param range A TextRange. - * @param end The new end position. - */ - function moveRangeEnd(range: TextRange, end: number): TextRange; - /** - * Creates a new TextRange from a provided range with a new start position. - * - * @param range A TextRange. - * @param pos The new Start position. - */ - function moveRangePos(range: TextRange, pos: number): TextRange; - /** - * Moves the start position of a range past any decorators. - */ - function moveRangePastDecorators(node: Node): TextRange; - /** - * Moves the start position of a range past any decorators or modifiers. - */ - function moveRangePastModifiers(node: Node): TextRange; - /** - * Determines whether a TextRange has the same start and end positions. - * - * @param range A TextRange. - */ - function isCollapsedRange(range: TextRange): boolean; - /** - * Creates a new TextRange for a token at the provides start position. - * - * @param pos The start position. - * @param token The token. - */ - function createTokenRange(pos: number, token: SyntaxKind): TextRange; - function rangeIsOnSingleLine(range: TextRange, sourceFile: SourceFile): boolean; - function rangeStartPositionsAreOnSameLine(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean; - function rangeEndPositionsAreOnSameLine(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean; - function rangeStartIsOnSameLineAsRangeEnd(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean; - function rangeEndIsOnSameLineAsRangeStart(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean; - function positionsAreOnSameLine(pos1: number, pos2: number, sourceFile: SourceFile): boolean; - function getStartPositionOfRange(range: TextRange, sourceFile: SourceFile): number; - /** - * Determines whether a name was originally the declaration name of an enum or namespace - * declaration. - */ - function isDeclarationNameOfEnumOrNamespace(node: Identifier): boolean; - function getInitializedVariables(node: VariableDeclarationList): ReadonlyArray; - function isWatchSet(options: CompilerOptions): boolean | undefined; - function closeFileWatcher(watcher: FileWatcher): void; - function getCheckFlags(symbol: Symbol): CheckFlags; - function getDeclarationModifierFlagsFromSymbol(s: Symbol): ModifierFlags; - function skipAlias(symbol: Symbol, checker: TypeChecker): Symbol; - /** See comment on `declareModuleMember` in `binder.ts`. */ - function getCombinedLocalAndExportSymbolFlags(symbol: Symbol): SymbolFlags; - function isWriteOnlyAccess(node: Node): boolean; - function isWriteAccess(node: Node): boolean; - function compareDataObjects(dst: any, src: any): boolean; - /** - * clears already present map by calling onDeleteExistingValue callback before deleting that key/value - */ - function clearMap(map: Map, onDeleteValue: (valueInMap: T, key: string) => void): void; - interface MutateMapOptions { - createNewValue(key: string, valueInNewMap: U): T; - onDeleteValue(existingValue: T, key: string): void; - /** - * If present this is called with the key when there is value for that key both in new map as well as existing map provided - * Caller can then decide to update or remove this key. - * If the key is removed, caller will get callback of createNewValue for that key. - * If this callback is not provided, the value of such keys is not updated. - */ - onExistingValue?(existingValue: T, valueInNewMap: U, key: string): void; - } - /** - * Mutates the map with newMap such that keys in map will be same as newMap. - */ - function mutateMap(map: Map, newMap: ReadonlyMap, options: MutateMapOptions): void; - /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ - function forEachAncestorDirectory(directory: string, callback: (directory: string) => T | undefined): T | undefined; - function isAbstractConstructorType(type: Type): boolean; - function isAbstractConstructorSymbol(symbol: Symbol): boolean; - function getClassLikeDeclarationOfSymbol(symbol: Symbol): ClassLikeDeclaration | undefined; - function getObjectFlags(type: Type): ObjectFlags; - function typeHasCallOrConstructSignatures(type: Type, checker: TypeChecker): boolean; - function forSomeAncestorDirectory(directory: string, callback: (directory: string) => boolean): boolean; - function isUMDExportSymbol(symbol: Symbol | undefined): boolean; - function showModuleSpecifier({ moduleSpecifier }: ImportDeclaration): string; - function getLastChild(node: Node): Node | undefined; - /** Add a value to a set, and return true if it wasn't already present. */ - function addToSeen(seen: Map, key: string | number): boolean; - function addToSeen(seen: Map, key: string | number, value: T): boolean; - function isObjectTypeDeclaration(node: Node): node is ObjectTypeDeclaration; -} declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; function textSpanEnd(span: TextSpan): number; function textSpanIsEmpty(span: TextSpan): boolean; function textSpanContainsPosition(span: TextSpan, position: number): boolean; - function textRangeContainsPositionInclusive(span: TextRange, position: number): boolean; function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined; @@ -6668,7 +3133,6 @@ declare namespace ts { function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined; function createTextSpan(start: number, length: number): TextSpan; - function createTextRange(pos: number, end?: number): TextRange; function createTextSpanFromBounds(start: number, end: number): TextSpan; function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; @@ -6729,6 +3193,8 @@ declare namespace ts { * @returns The original parse tree node if found; otherwise, undefined. */ function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier: string): __String; /** * Remove extra underscore from escaped identifier text content. * @@ -6739,12 +3205,6 @@ declare namespace ts { function idText(identifier: Identifier): string; function symbolName(symbol: Symbol): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; - /** @internal */ - function isNamedDeclaration(node: Node): node is NamedDeclaration & { - name: DeclarationName; - }; - /** @internal */ - function getNonAssignedNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; /** * Gets the JSDoc parameter tags for the node if present. @@ -6771,6 +3231,8 @@ declare namespace ts { 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 enum tag for the node if present */ + function getJSDocEnumTag(node: Node): JSDocEnumTag | undefined; /** Gets the JSDoc this tag for the node if present */ function getJSDocThisTag(node: Node): JSDocThisTag | undefined; /** Gets the JSDoc return tag for the node if present */ @@ -6792,16 +3254,22 @@ declare namespace ts { */ function getJSDocType(node: Node): TypeNode | undefined; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): ReadonlyArray; /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray; + function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -6828,7 +3296,6 @@ declare namespace ts { function isCallSignatureDeclaration(node: Node): node is CallSignatureDeclaration; function isConstructSignatureDeclaration(node: Node): node is ConstructSignatureDeclaration; function isIndexSignatureDeclaration(node: Node): node is IndexSignatureDeclaration; - function isGetOrSetAccessorDeclaration(node: Node): node is AccessorDeclaration; function isTypePredicateNode(node: Node): node is TypePredicateNode; function isTypeReferenceNode(node: Node): node is TypeReferenceNode; function isFunctionTypeNode(node: Node): node is FunctionTypeNode; @@ -6959,6 +3426,7 @@ declare namespace ts { function isJSDoc(node: Node): node is JSDoc; function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; function isJSDocClassTag(node: Node): node is JSDocClassTag; + function isJSDocEnumTag(node: Node): node is JSDocEnumTag; function isJSDocThisTag(node: Node): node is JSDocThisTag; function isJSDocParameterTag(node: Node): node is JSDocParameterTag; function isJSDocReturnTag(node: Node): node is JSDocReturnTag; @@ -6972,39 +3440,25 @@ declare namespace ts { function isJSDocSignature(node: Node): node is JSDocSignature; } declare namespace ts { - function isSyntaxList(n: Node): n is SyntaxList; - function isNode(node: Node): boolean; - function isNodeKind(kind: SyntaxKind): boolean; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n: Node): boolean; - function isNodeArray(array: ReadonlyArray): array is NodeArray; - function isLiteralKind(kind: SyntaxKind): boolean; function isLiteralExpression(node: Node): node is LiteralExpression; - function isTemplateLiteralKind(kind: SyntaxKind): boolean; type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail; function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; - function isGeneratedIdentifier(node: Node): node is GeneratedIdentifier; - function isModifierKind(token: SyntaxKind): token is Modifier["kind"]; - function isParameterPropertyModifier(kind: SyntaxKind): boolean; - function isClassMemberModifier(idToken: SyntaxKind): boolean; function isModifier(node: Node): node is Modifier; function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; function isBindingName(node: Node): node is BindingName; function isFunctionLike(node: Node): node is SignatureDeclaration; - function isFunctionLikeDeclaration(node: Node): node is FunctionLikeDeclaration; - function isFunctionLikeKind(kind: SyntaxKind): boolean; - function isFunctionOrModuleBlock(node: Node): boolean; function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; - function isMethodOrAccessor(node: Node): node is MethodDeclaration | AccessorDeclaration; function isTypeElement(node: Node): node is TypeElement; function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; @@ -7015,409 +3469,24 @@ declare namespace ts { */ function isTypeNode(node: Node): node is TypeNode; function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode; - function isBindingPattern(node: Node | undefined): node is BindingPattern; - function isAssignmentPattern(node: Node): node is AssignmentPattern; - function isArrayBindingElement(node: Node): node is ArrayBindingElement; - /** - * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration - */ - function isDeclarationBindingElement(bindingElement: BindingOrAssignmentElement): bindingElement is VariableDeclaration | ParameterDeclaration | BindingElement; - /** - * Determines whether a node is a BindingOrAssignmentPattern - */ - function isBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is BindingOrAssignmentPattern; - /** - * Determines whether a node is an ObjectBindingOrAssignmentPattern - */ - function isObjectBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ObjectBindingOrAssignmentPattern; - /** - * Determines whether a node is an ArrayBindingOrAssignmentPattern - */ - function isArrayBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ArrayBindingOrAssignmentPattern; - function isPropertyAccessOrQualifiedNameOrImportTypeNode(node: Node): node is PropertyAccessExpression | QualifiedName | ImportTypeNode; function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName; function isCallLikeExpression(node: Node): node is CallLikeExpression; function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; function isTemplateLiteral(node: Node): node is TemplateLiteral; - function isLeftHandSideExpression(node: Node): node is LeftHandSideExpression; - function isUnaryExpression(node: Node): node is UnaryExpression; - function isUnaryExpressionWithWrite(expr: Node): expr is PrefixUnaryExpression | PostfixUnaryExpression; - /** - * Determines whether a node is an expression based only on its kind. - * Use `isExpressionNode` if not in transforms. - */ - function isExpression(node: Node): node is Expression; function isAssertionExpression(node: Node): node is AssertionExpression; - function isPartiallyEmittedExpression(node: Node): node is PartiallyEmittedExpression; - function isNotEmittedStatement(node: Node): node is NotEmittedStatement; - function isNotEmittedOrPartiallyEmittedNode(node: Node): node is NotEmittedStatement | PartiallyEmittedExpression; function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement; function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement; - function isForInOrOfStatement(node: Node): node is ForInOrOfStatement; - function isConciseBody(node: Node): node is ConciseBody; - function isFunctionBody(node: Node): node is FunctionBody; - function isForInitializer(node: Node): node is ForInitializer; - function isModuleBody(node: Node): node is ModuleBody; - function isNamespaceBody(node: Node): node is NamespaceBody; - function isJSDocNamespaceBody(node: Node): node is JSDocNamespaceBody; - function isNamedImportBindings(node: Node): node is NamedImportBindings; - function isModuleOrEnumDeclaration(node: Node): node is ModuleDeclaration | EnumDeclaration; - function isDeclaration(node: Node): node is NamedDeclaration; - function isDeclarationStatement(node: Node): node is DeclarationStatement; - /** - * Determines whether the node is a statement that is not also a declaration - */ - function isStatementButNotDeclaration(node: Node): node is Statement; - function isStatement(node: Node): node is Statement; - function isModuleReference(node: Node): node is ModuleReference; - function isJsxTagNameExpression(node: Node): node is JsxTagNameExpression; - function isJsxChild(node: Node): node is JsxChild; - function isJsxAttributeLike(node: Node): node is JsxAttributeLike; - function isStringLiteralOrJsxExpression(node: Node): node is StringLiteral | JsxExpression; function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; - /** True if node is of some JSDoc syntax kind. */ - function isJSDocNode(node: Node): boolean; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node: Node): boolean; - function isJSDocTag(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; - /** True if has jsdoc nodes attached to it. */ - function hasJSDocNodes(node: Node): node is HasJSDoc; - /** True if has type node attached to it. */ - function hasType(node: Node): node is HasType; - function couldHaveType(node: Node): node is HasType; - /** True if has initializer node attached to it. */ - function hasInitializer(node: Node): node is HasInitializer; - /** True if has initializer node attached to it. */ - function hasOnlyExpressionInitializer(node: Node): node is HasExpressionInitializer; function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; - function isTypeReferenceType(node: Node): node is TypeReferenceType; - function guessIndentation(lines: string[]): number | undefined; function isStringLiteralLike(node: Node): node is StringLiteralLike; } -declare namespace ts { - /** @internal */ - function isNamedImportsOrExports(node: Node): node is NamedImportsOrExports; - interface ObjectAllocator { - getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node; - getTokenConstructor(): new (kind: TKind, pos?: number, end?: number) => Token; - getIdentifierConstructor(): new (kind: SyntaxKind.Identifier, pos?: number, end?: number) => Identifier; - getSourceFileConstructor(): new (kind: SyntaxKind.SourceFile, pos?: number, end?: number) => SourceFile; - getSymbolConstructor(): new (flags: SymbolFlags, name: __String) => Symbol; - getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; - getSignatureConstructor(): new (checker: TypeChecker) => Signature; - getSourceMapSourceConstructor(): new (fileName: string, text: string, skipTrivia?: (pos: number) => number) => SourceMapSource; - } - let objectAllocator: ObjectAllocator; - function formatStringFromArgs(text: string, args: ArrayLike, baseIndex?: number): string; - let localizedDiagnosticMessages: MapLike | undefined; - function getLocaleSpecificMessage(message: DiagnosticMessage): string; - function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: (string | number | undefined)[]): DiagnosticWithLocation; - function formatMessage(_dummy: any, message: DiagnosticMessage): string; - function createCompilerDiagnostic(message: DiagnosticMessage, ...args: (string | number | undefined)[]): Diagnostic; - function createCompilerDiagnosticFromMessageChain(chain: DiagnosticMessageChain): Diagnostic; - function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage, ...args: (string | undefined)[]): DiagnosticMessageChain; - function concatenateDiagnosticMessageChains(headChain: DiagnosticMessageChain, tailChain: DiagnosticMessageChain): DiagnosticMessageChain; - function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): Comparison; - function compareDiagnosticsSkipRelatedInformation(d1: Diagnostic, d2: Diagnostic): Comparison; - function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget; - function getEmitModuleKind(compilerOptions: { - module?: CompilerOptions["module"]; - target?: CompilerOptions["target"]; - }): ModuleKind; - function getEmitModuleResolutionKind(compilerOptions: CompilerOptions): ModuleResolutionKind; - function unreachableCodeIsError(options: CompilerOptions): boolean; - function unusedLabelIsError(options: CompilerOptions): boolean; - function getAreDeclarationMapsEnabled(options: CompilerOptions): boolean; - function getAllowSyntheticDefaultImports(compilerOptions: CompilerOptions): boolean; - function getEmitDeclarations(compilerOptions: CompilerOptions): boolean; - type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "strictPropertyInitialization" | "alwaysStrict"; - function getStrictOptionValue(compilerOptions: CompilerOptions, flag: StrictOptionName): boolean; - function hasZeroOrOneAsteriskCharacter(str: string): boolean; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - const directorySeparator = "/"; - /** - * Normalize path separators. - */ - function normalizeSlashes(path: string): string; - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path: string): number; - function normalizePath(path: string): string; - function normalizePathAndParts(path: string): { - path: string; - parts: string[]; - }; - /** - * Returns the path except for its basename. Semantics align with NodeJS's `path.dirname` - * except that we support URL's as well. - * - * ```ts - * getDirectoryPath("/path/to/file.ext") === "/path/to" - * getDirectoryPath("/path/to/") === "/path" - * getDirectoryPath("/") === "/" - * ``` - */ - function getDirectoryPath(path: Path): Path; - /** - * Returns the path except for its basename. Semantics align with NodeJS's `path.dirname` - * except that we support URL's as well. - * - * ```ts - * getDirectoryPath("/path/to/file.ext") === "/path/to" - * getDirectoryPath("/path/to/") === "/path" - * getDirectoryPath("/") === "/" - * ``` - */ - function getDirectoryPath(path: string): string; - function isUrl(path: string): boolean; - function pathIsRelative(path: string): boolean; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path: string): boolean; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path: string): boolean; - function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path: string, currentDirectory?: string): string[]; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components: ReadonlyArray): string[]; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path: string, currentDirectory: string | undefined): string[]; - function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined): string; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents: ReadonlyArray): string; -} -declare namespace ts { - function getPathComponentsRelativeTo(from: string, to: string, stringEqualityComparer: (a: string, b: string) => boolean, getCanonicalFileName: GetCanonicalFileName): string[]; - function getRelativePathFromFile(from: string, to: string, getCanonicalFileName: GetCanonicalFileName): string; - /** - * Gets a relative path that can be used to traverse between `from` and `to`. - */ - function getRelativePathFromDirectory(from: string, to: string, ignoreCase: boolean): string; - /** - * Gets a relative path that can be used to traverse between `from` and `to`. - */ - function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileName: GetCanonicalFileName): string; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, isAbsolutePathAnUrl: boolean): string; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path: string): string; - /** - * Returns the path except for its containing directory name. - * Semantics align with NodeJS's `path.basename` except that we support URL's as well. - * - * ```ts - * getBaseFileName("/path/to/file.ext") === "file.ext" - * getBaseFileName("/path/to/") === "to" - * getBaseFileName("/") === "" - * ``` - */ - function getBaseFileName(path: string): string; - /** - * Gets the portion of a path following the last (non-terminal) separator (`/`). - * Semantics align with NodeJS's `path.basename` except that we support URL's as well. - * If the base name has any one of the provided extensions, it is removed. - * - * ```ts - * getBaseFileName("/path/to/file.ext", ".ext", true) === "file" - * getBaseFileName("/path/to/file.js", ".ext", true) === "file.js" - * ``` - */ - function getBaseFileName(path: string, extensions: string | ReadonlyArray, ignoreCase: boolean): string; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path: string, ...paths: (string | undefined)[]): string; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path: string, ...paths: (string | undefined)[]): string; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path: string): boolean; - /** - * Removes a trailing directory separator from a path. - * @param path The path. - */ - function removeTrailingDirectorySeparator(path: Path): Path; - function removeTrailingDirectorySeparator(path: string): string; - /** - * Adds a trailing directory separator to a path, if it does not already have one. - * @param path The path. - */ - function ensureTrailingDirectorySeparator(path: Path): Path; - function ensureTrailingDirectorySeparator(path: string): string; - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a: string, b: string): Comparison; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a: string, b: string): Comparison; - function comparePaths(a: string, b: string, ignoreCase?: boolean): Comparison; - function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison; - function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean; - function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean; - function tryRemoveDirectoryPrefix(path: string, dirPath: string, getCanonicalFileName: GetCanonicalFileName): string | undefined; - function hasExtension(fileName: string): boolean; - const commonPackageFolders: ReadonlyArray; - function getRegularExpressionForWildcard(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string | undefined; - /** - * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, - * and does not contain any glob characters itself. - */ - function isImplicitGlob(lastPathComponent: string): boolean; - interface FileSystemEntries { - readonly files: ReadonlyArray; - readonly directories: ReadonlyArray; - } - interface FileMatcherPatterns { - /** One pattern for each "include" spec. */ - includeFilePatterns: ReadonlyArray | undefined; - /** One pattern matching one of any of the "include" specs. */ - includeFilePattern: string | undefined; - includeDirectoryPattern: string | undefined; - excludePattern: string | undefined; - basePaths: ReadonlyArray; - } - /** @param path directory of the tsconfig.json */ - function getFileMatcherPatterns(path: string, excludes: ReadonlyArray | undefined, includes: ReadonlyArray | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns; - function getRegexFromPattern(pattern: string, useCaseSensitiveFileNames: boolean): RegExp; - /** @param path directory of the tsconfig.json */ - function matchFiles(path: string, extensions: ReadonlyArray | undefined, excludes: ReadonlyArray | undefined, includes: ReadonlyArray | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries): string[]; - function ensureScriptKind(fileName: string, scriptKind: ScriptKind | undefined): ScriptKind; - function getScriptKindFromFileName(fileName: string): ScriptKind; - /** - * List of supported extensions in order of file resolution precedence. - */ - const supportedTypeScriptExtensions: ReadonlyArray; - /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - const supportedTypescriptExtensionsForExtractExtension: ReadonlyArray; - const supportedJavascriptExtensions: ReadonlyArray; - function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray; - function hasJavaScriptFileExtension(fileName: string): boolean; - function hasTypeScriptFileExtension(fileName: string): boolean; - function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: ReadonlyArray): boolean; - /** - * Extension boundaries by priority. Lower numbers indicate higher priorities, and are - * aligned to the offset of the highest priority extension in the - * allSupportedExtensions array. - */ - enum ExtensionPriority { - TypeScriptFiles = 0, - DeclarationAndJavaScriptFiles = 2, - Highest = 0, - Lowest = 2 - } - function getExtensionPriority(path: string, supportedExtensions: ReadonlyArray): ExtensionPriority; - /** - * Adjusts an extension priority to be the highest priority within the same range. - */ - function adjustExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: ReadonlyArray): ExtensionPriority; - /** - * Gets the next lowest extension priority for a given priority. - */ - function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: ReadonlyArray): ExtensionPriority; - function removeFileExtension(path: string): string; - function tryRemoveExtension(path: string, extension: string): string | undefined; - function removeExtension(path: string, extension: string): string; - function changeExtension(path: T, newExtension: string): T; - function changeAnyExtension(path: string, ext: string): string; - function changeAnyExtension(path: string, ext: string, extensions: string | ReadonlyArray, ignoreCase: boolean): string; - namespace Debug { - function showSymbol(symbol: Symbol): string; - function showSyntaxKind(node: Node): string; - } - function tryParsePattern(pattern: string): Pattern | undefined; - function positionIsSynthesized(pos: number): boolean; - /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext: Extension): boolean; - function resolutionExtensionIsTypeScriptOrJson(ext: Extension): boolean; - /** - * Gets the extension from a path. - * Path must have a valid extension. - */ - function extensionFromPath(path: string): Extension; - function isAnySupportedFileExtension(path: string): boolean; - function tryGetExtensionFromPath(path: string): Extension | undefined; - /** - * Gets the file extension for a path. - */ - function getAnyExtensionFromPath(path: string): string; - /** - * Gets the file extension for a path, provided it is one of the provided extensions. - */ - function getAnyExtensionFromPath(path: string, extensions: string | ReadonlyArray, ignoreCase: boolean): string; - function isCheckJsEnabledForFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean | undefined; - const emptyFileSystemEntries: FileSystemEntries; - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings: ReadonlyArray, candidate: string): string | Pattern | undefined; - type Mutable = { - -readonly [K in keyof T]: T[K]; - }; -} declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; - function isJSDocLikeText(text: string, start: number): boolean; /** * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, @@ -7442,60 +3511,9 @@ declare namespace ts { function parseJsonText(fileName: string, sourceText: string): JsonSourceFile; function isExternalModule(file: SourceFile): boolean; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function parseIsolatedJSDocComment(content: string, start?: number, length?: number): { - jsDoc: JSDoc; - diagnostics: Diagnostic[]; - } | undefined; - function parseJSDocTypeExpressionForTests(content: string, start?: number, length?: number): { - jsDocTypeExpression: JSDocTypeExpression; - diagnostics: Diagnostic[]; - } | undefined; - interface PragmaContext { - languageVersion: ScriptTarget; - pragmas?: PragmaMap; - checkJsDirective?: CheckJsDirective; - referencedFiles: FileReference[]; - typeReferenceDirectives: FileReference[]; - libReferenceDirectives: FileReference[]; - amdDependencies: AmdDependency[]; - hasNoDefaultLib?: boolean; - moduleName?: string; - } - function processCommentPragmas(context: PragmaContext, sourceText: string): void; - type PragmaDiagnosticReporter = (pos: number, length: number, message: DiagnosticMessage) => void; - function processPragmasIntoFields(context: PragmaContext, reportDiagnostic: PragmaDiagnosticReporter): void; - /** @internal */ - function tagNamesAreEquivalent(lhs: JsxTagNameExpression, rhs: JsxTagNameExpression): boolean; } declare namespace ts { - const compileOnSaveCommandLineOption: CommandLineOption; - /** - * An array of supported "lib" reference file names used to determine the order for inclusion - * when referenced, as well as for spelling suggestions. This ensures the correct ordering for - * overload resolution when a type declared in one lib is extended by another. - */ - const libs: string[]; - /** - * A map of lib names to lib files. This map is used both for parsing the "lib" command line - * option as well as for resolving lib reference directives. - */ - const libMap: Map; - const optionDeclarations: CommandLineOption[]; - const typeAcquisitionDeclarations: CommandLineOption[]; - interface OptionNameMap { - optionNameMap: Map; - shortOptionNames: Map; - } - const defaultInitCompilerOptions: CompilerOptions; - function convertEnableAutoDiscoveryToEnable(typeAcquisition: TypeAcquisition): TypeAcquisition; - function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic; - function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Push): string | number | undefined; - function parseListTypeOption(opt: CommandLineOptionOfListType, value: string | undefined, errors: Push): (string | number)[] | undefined; function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; - /** @internal */ - function getOptionFromName(optionName: string, allowShort?: boolean): CommandLineOption | undefined; - function printVersion(): void; - function printHelp(optionsList: CommandLineOption[], syntaxPrefix?: string): void; type DiagnosticReporter = (diagnostic: Diagnostic) => void; /** * Reports config file diagnostics @@ -7538,49 +3556,10 @@ declare namespace ts { * @param fileName The path to the config file */ function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile; - interface JsonConversionNotifier { - /** - * Notifies parent option object is being set with the optionKey and a valid optionValue - * Currently it notifies only if there is element with type object (parentOption) and - * has element's option declarations map associated with it - * @param parentOption parent option name in which the option and value are being set - * @param option option declaration which is being set with the value - * @param value value of the option - */ - onSetValidOptionKeyValueInParent(parentOption: string, option: CommandLineOption, value: CompilerOptionsValue): void; - /** - * Notify when valid root key value option is being set - * @param key option key - * @param keyNode node corresponding to node in the source file - * @param value computed value of the key - * @param ValueNode node corresponding to value in the source file - */ - onSetValidOptionKeyValueInRoot(key: string, keyNode: PropertyName, value: CompilerOptionsValue, valueNode: Expression): void; - /** - * Notify when unknown root key value option is being set - * @param key option key - * @param keyNode node corresponding to node in the source file - * @param value computed value of the key - * @param ValueNode node corresponding to value in the source file - */ - onSetUnknownOptionKeyValueInRoot(key: string, keyNode: PropertyName, value: CompilerOptionsValue, valueNode: Expression): void; - } /** * Convert the json syntax tree into the json value */ function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; - /** - * Convert the json syntax tree into the json value and report errors - * This returns the json value (apart from checking errors) only if returnValue provided is true. - * Otherwise it just checks the errors and returns undefined - */ - function convertToObjectWorker(sourceFile: JsonSourceFile, errors: Push, returnValue: boolean, knownRootOptions: CommandLineOption | undefined, jsonConversionNotifier: JsonConversionNotifier | undefined): any; - /** - * Generate tsconfig configuration when running command line "--init" - * @param options commandlineOptions to be generated into tsconfig.json - * @param fileNames array of filenames to be generated into tsconfig.json - */ - function generateTSConfig(options: CompilerOptions, fileNames: ReadonlyArray, newLine: string): string; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -7597,9 +3576,6 @@ declare namespace ts { * file to. e.g. outDir */ function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; - function setConfigFileInOptions(options: CompilerOptions, configFile: TsConfigSourceFile | undefined): void; - function isErrorNoInputFiles(error: Diagnostic): boolean; - function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }: ConfigFileSpecs, configFileName: string | undefined): Diagnostic; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -7608,32 +3584,8 @@ declare namespace ts { options: TypeAcquisition; errors: Diagnostic[]; }; - /** - * Gets the file names from the provided config file specs that contain, files, include, exclude and - * other properties needed to resolve the file names - * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details - * @param basePath The base path for any relative file specifications. - * @param options Compiler options. - * @param host The host used to resolve files and directories. - * @param extraFileExtensions optionaly file extra file extension information from host - */ - function getFileNamesFromConfigSpecs(spec: ConfigFileSpecs, basePath: string, options: CompilerOptions, host: ParseConfigHost, extraFileExtensions?: ReadonlyArray): ExpandResult; - /** - * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. - * Also converts enum values back to strings. - */ - function convertCompilerOptionsForTelemetry(opts: CompilerOptions): CompilerOptions; } declare namespace ts { - function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; - function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean; - /** Array that is only intended to be pushed to, never read. */ - interface Push { - push(value: T): void; - } - function readJson(path: string, host: { - readFile(fileName: string): string | undefined; - }): object; function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. @@ -7669,78 +3621,13 @@ declare namespace ts { set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap: Map>, moduleNameToDirectoryMap: Map, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName): ModuleResolutionCache; function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - /** - * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. - * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 - * Throws an error if the module can't be resolved. - */ - function resolveJavaScriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string; - function directoryProbablyExists(directoryName: string, host: { - directoryExists?: (directoryName: string) => boolean; - }): boolean; - function getPackageName(moduleName: string): { - packageName: string; - rest: string; - }; - function getTypesPackageName(packageName: string): string; - function getMangledNameForScopedPackage(packageName: string): string; - function getPackageNameFromAtTypesDirectory(mangledName: string): string; - function getUnmangledNameForScopedPackage(typesPackageName: string): string; function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; - /** - * LSHost may load a module from a global cache of typings. - * This is the minumum code needed to expose that functionality; the rest is in LSHost. - */ - function loadModuleFromGlobalCache(moduleName: string, projectName: string | undefined, compilerOptions: CompilerOptions, host: ModuleResolutionHost, globalCache: string): ResolvedModuleWithFailedLookupLocations; -} -declare namespace ts { - enum ModuleInstanceState { - NonInstantiated = 0, - Instantiated = 1, - ConstEnumOnly = 2 - } - function getModuleInstanceState(node: ModuleDeclaration): ModuleInstanceState; - function bindSourceFile(file: SourceFile, options: CompilerOptions): void; - function isExportsOrModuleExportsOrAlias(sourceFile: SourceFile, node: Expression): boolean; - /** - * Computes the transform flags for a node, given the transform flags of its subtree - * - * @param node The node to analyze - * @param subtreeFlags Transform flags computed for this node's subtree - */ - function computeTransformFlagsForNode(node: Node, subtreeFlags: TransformFlags): TransformFlags; - /** - * Gets the transform flags to exclude when unioning the transform flags of a subtree. - * - * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. - * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather - * than calling this function. - */ - function getTransformFlagsSubtreeExclusions(kind: SyntaxKind): TransformFlags; -} -/** @internal */ -declare namespace ts { - function createGetSymbolWalker(getRestTypeOfSignature: (sig: Signature) => Type, getTypePredicateOfSignature: (sig: Signature) => TypePredicate | undefined, getReturnTypeOfSignature: (sig: Signature) => Type, getBaseTypes: (type: Type) => Type[], resolveStructuredTypeMembers: (type: ObjectType) => ResolvedType, getTypeOfSymbol: (sym: Symbol) => Type, getResolvedSymbol: (node: Node) => Symbol, getIndexTypeOfStructuredType: (type: Type, kind: IndexKind) => Type | undefined, getConstraintFromTypeParameter: (typeParameter: TypeParameter) => Type | undefined, getFirstIdentifier: (node: EntityNameOrEntityNameExpression) => Identifier): (accept?: (symbol: Symbol) => boolean) => SymbolWalker; -} -declare namespace ts { - function getNodeId(node: Node): number; - function getSymbolId(symbol: Symbol): number; - function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean; - function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker; } declare namespace ts { - function updateNode(updated: T, original: T): T; - function createNodeArray(elements?: T[], hasTrailingComma?: boolean): MutableNodeArray; function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; - /** - * Creates a shallow, memberwise clone of a node with no source map location. - */ - function getSynthesizedClone(node: T): T; - function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier, isSingleQuote: boolean): StringLiteral; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; @@ -7750,24 +3637,19 @@ declare namespace ts { function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; - function createIdentifier(text: string, typeArguments: ReadonlyArray | undefined): Identifier; function updateIdentifier(node: Identifier): Identifier; - function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; - function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes: boolean): GeneratedIdentifier; /** Create a unique temporary variable for use in a loop. */ function createLoopVariable(): Identifier; /** Create a unique name based on the supplied text. */ function createUniqueName(text: string): Identifier; - function createOptimisticUniqueName(text: string): GeneratedIdentifier; /** Create a unique name based on the supplied text. */ function createOptimisticUniqueName(text: string): Identifier; /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ function createFileLevelUniqueName(text: string): Identifier; /** Create a unique name generated for a node. */ function getGeneratedNameForNode(node: Node | undefined): Identifier; - function getGeneratedNameForNode(node: Node | undefined, flags: GeneratedIdentifierFlags): Identifier; function createToken(token: TKind): Token; function createSuper(): SuperExpression; function createThis(): ThisExpression & Token; @@ -7806,7 +3688,6 @@ declare namespace ts { function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; function createIndexSignature(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; function updateIndexSignature(node: IndexSignatureDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; - function createSignatureDeclaration(kind: SyntaxKind, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, typeArguments?: ReadonlyArray | undefined): SignatureDeclaration; function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode; function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode; function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; @@ -7869,11 +3750,9 @@ declare namespace ts { function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; - function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + /** @deprecated */ function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; - /** @internal */ - function createTaggedTemplate(tag: Expression, typeArgumentsOrTemplate: ReadonlyArray | TemplateLiteral | undefined, template?: TemplateLiteral): TaggedTemplateExpression; - function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + /** @deprecated */ function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; @@ -7882,7 +3761,6 @@ declare namespace ts { function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; 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; - /** @deprecated */ 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; @@ -7898,9 +3776,8 @@ declare namespace ts { function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; - function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + /** @deprecated */ function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; - /** @deprecated */ 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; @@ -8057,16 +3934,6 @@ declare namespace ts { * @param original The original statement. */ function createNotEmittedStatement(original: Node): NotEmittedStatement; - /** - * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in - * order to properly emit exports. - */ - function createEndOfDeclarationMarker(original: Node): EndOfDeclarationMarker; - /** - * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in - * order to properly emit exports. - */ - function createMergeDeclarationMarker(original: Node): MergeDeclarationMarker; /** * Creates a synthetic expression to act as a placeholder for a not-emitted expression in * order to preserve comments or sourcemap positions. @@ -8109,20 +3976,11 @@ declare namespace ts { * @param sourceFile A source file. */ function disposeEmitNodes(sourceFile: SourceFile): void; - /** - * Associates a node with the current transformation, initializing - * various transient transformation properties. - */ - function getOrCreateEmitNode(node: Node): EmitNode; function setTextRange(range: T, location: TextRange | undefined): T; /** * Sets flags that control emit behavior of a node. */ function setEmitFlags(node: T, emitFlags: EmitFlags): T; - /** - * Sets flags that control emit behavior of a node. - */ - function addEmitFlags(node: T, emitFlags: EmitFlags): T; /** * Gets a custom text range to use when emitting source maps. */ @@ -8143,14 +4001,6 @@ declare namespace ts { * Sets the TextRange to use for source maps for a token of a node. */ function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T; - /** - * Gets a custom text range to use when emitting comments. - */ - function getStartsOnNewLine(node: Node): boolean | undefined; - /** - * Sets a custom text range to use when emitting comments. - */ - function setStartsOnNewLine(node: T, newLine: boolean): T; /** * Gets a custom text range to use when emitting comments. */ @@ -8194,265 +4044,8 @@ declare namespace ts { * Moves matching emit helpers from a source node to a target node. */ function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; - function compareEmitHelpers(x: EmitHelper, y: EmitHelper): Comparison; function setOriginalNode(node: T, original: Node | undefined): T; } -declare namespace ts { - const nullTransformationContext: TransformationContext; - type TypeOfTag = "undefined" | "number" | "boolean" | "string" | "symbol" | "object" | "function"; - function createTypeCheck(value: Expression, tag: TypeOfTag): BinaryExpression; - function createMemberAccessForPropertyName(target: Expression, memberName: PropertyName, location?: TextRange): MemberExpression; - function createFunctionCall(func: Expression, thisArg: Expression, argumentsList: ReadonlyArray, location?: TextRange): CallExpression; - function createFunctionApply(func: Expression, thisArg: Expression, argumentsExpression: Expression, location?: TextRange): CallExpression; - function createArraySlice(array: Expression, start?: number | Expression): CallExpression; - function createArrayConcat(array: Expression, values: ReadonlyArray): CallExpression; - function createMathPow(left: Expression, right: Expression, location?: TextRange): CallExpression; - function createExpressionForJsxElement(jsxFactoryEntity: EntityName | undefined, reactNamespace: string, tagName: Expression, props: Expression, children: ReadonlyArray, parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression; - function createExpressionForJsxFragment(jsxFactoryEntity: EntityName | undefined, reactNamespace: string, children: ReadonlyArray, parentElement: JsxOpeningFragment, location: TextRange): LeftHandSideExpression; - function getHelperName(name: string): Identifier; - function createValuesHelper(context: TransformationContext, expression: Expression, location?: TextRange): CallExpression; - function createReadHelper(context: TransformationContext, iteratorRecord: Expression, count: number | undefined, location?: TextRange): CallExpression; - function createSpreadHelper(context: TransformationContext, argumentList: ReadonlyArray, location?: TextRange): CallExpression; - function createForOfBindingStatement(node: ForInitializer, boundValue: Expression): Statement; - function insertLeadingStatement(dest: Statement, source: Statement): Block; - function restoreEnclosingLabel(node: Statement, outermostLabeledStatement: LabeledStatement | undefined, afterRestoreLabelCallback?: (node: LabeledStatement) => void): Statement; - interface CallBinding { - target: LeftHandSideExpression; - thisArg: Expression; - } - function createCallBinding(expression: Expression, recordTempVariable: (temp: Identifier) => void, languageVersion?: ScriptTarget, cacheIdentifiers?: boolean): CallBinding; - function inlineExpressions(expressions: ReadonlyArray): Expression; - function createExpressionFromEntityName(node: EntityName | Expression): Expression; - function createExpressionForPropertyName(memberName: PropertyName): Expression; - function createExpressionForObjectLiteralElementLike(node: ObjectLiteralExpression, property: ObjectLiteralElementLike, receiver: Expression): Expression | undefined; - /** - * Gets the internal name of a declaration. This is primarily used for declarations that can be - * referred to by name in the body of an ES5 class function body. An internal name will *never* - * be prefixed with an module or namespace export modifier like "exports." when emitted as an - * expression. An internal name will also *never* be renamed due to a collision with a block - * scoped variable. - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - */ - function getInternalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; - /** - * Gets whether an identifier should only be referred to by its internal name. - */ - function isInternalName(node: Identifier): boolean; - /** - * Gets the local name of a declaration. This is primarily used for declarations that can be - * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A - * local name will *never* be prefixed with an module or namespace export modifier like - * "exports." when emitted as an expression. - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - */ - function getLocalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; - /** - * Gets whether an identifier should only be referred to by its local name. - */ - function isLocalName(node: Identifier): boolean; - /** - * Gets the export name of a declaration. This is primarily used for declarations that can be - * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An - * export name will *always* be prefixed with an module or namespace export modifier like - * `"exports."` when emitted as an expression if the name points to an exported symbol. - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - */ - function getExportName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; - /** - * Gets whether an identifier should only be referred to by its export representation if the - * name points to an exported symbol. - */ - function isExportName(node: Identifier): boolean; - /** - * Gets the name of a declaration for use in declarations. - * - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - */ - function getDeclarationName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; - /** - * Gets the exported name of a declaration for use in expressions. - * - * An exported name will *always* be prefixed with an module or namespace export modifier like - * "exports." if the name points to an exported symbol. - * - * @param ns The namespace identifier. - * @param node The declaration. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - */ - function getExternalModuleOrNamespaceExportName(ns: Identifier | undefined, node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier | PropertyAccessExpression; - /** - * Gets a namespace-qualified name for use in expressions. - * - * @param ns The namespace identifier. - * @param name The name. - * @param allowComments A value indicating whether comments may be emitted for the name. - * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. - */ - function getNamespaceMemberName(ns: Identifier, name: Identifier, allowComments?: boolean, allowSourceMaps?: boolean): PropertyAccessExpression; - function convertToFunctionBody(node: ConciseBody, multiLine?: boolean): Block; - function convertFunctionDeclarationToExpression(node: FunctionDeclaration): FunctionExpression; - /** - * Add any necessary prologue-directives into target statement-array. - * The function needs to be called during each transformation step. - * This function needs to be called whenever we transform the statement - * list of a source file, namespace, or function-like body. - * - * @param target: result statements array - * @param source: origin statements array - * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives - * @param visitor: Optional callback used to visit any custom prologue directives. - */ - function addPrologue(target: Statement[], source: ReadonlyArray, ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number; - /** - * Add just the standard (string-expression) prologue-directives into target statement-array. - * The function needs to be called during each transformation step. - * This function needs to be called whenever we transform the statement - * list of a source file, namespace, or function-like body. - */ - function addStandardPrologue(target: Statement[], source: ReadonlyArray, ensureUseStrict?: boolean): number; - /** - * Add just the custom prologue-directives into target statement-array. - * The function needs to be called during each transformation step. - * This function needs to be called whenever we transform the statement - * list of a source file, namespace, or function-like body. - */ - function addCustomPrologue(target: Statement[], source: ReadonlyArray, statementOffset: number, visitor?: (node: Node) => VisitResult): number; - function addCustomPrologue(target: Statement[], source: ReadonlyArray, statementOffset: number | undefined, visitor?: (node: Node) => VisitResult): number | undefined; - function startsWithUseStrict(statements: ReadonlyArray): boolean; - /** - * Ensures "use strict" directive is added - * - * @param statements An array of statements - */ - function ensureUseStrict(statements: NodeArray): NodeArray; - /** - * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended - * order of operations. - * - * @param binaryOperator The operator for the BinaryExpression. - * @param operand The operand for the BinaryExpression. - * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the - * BinaryExpression. - */ - function parenthesizeBinaryOperand(binaryOperator: SyntaxKind, operand: Expression, isLeftSideOfBinary: boolean, leftOperand?: Expression): Expression; - function parenthesizeForConditionalHead(condition: Expression): Expression; - function parenthesizeSubexpressionOfConditionalExpression(e: Expression): Expression; - /** - * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but - * has a lookahead restriction for `function`, `async function`, and `class`. - * - * Basically, that means we need to parenthesize in the following cases: - * - * - BinaryExpression of CommaToken - * - CommaList (synthetic list of multiple comma expressions) - * - FunctionExpression - * - ClassExpression - */ - function parenthesizeDefaultExpression(e: Expression): Expression; - /** - * Wraps an expression in parentheses if it is needed in order to use the expression - * as the expression of a NewExpression node. - * - * @param expression The Expression node. - */ - function parenthesizeForNew(expression: Expression): LeftHandSideExpression; - /** - * Wraps an expression in parentheses if it is needed in order to use the expression for - * property or element access. - * - * @param expr The expression node. - */ - function parenthesizeForAccess(expression: Expression): LeftHandSideExpression; - function parenthesizePostfixOperand(operand: Expression): LeftHandSideExpression; - function parenthesizePrefixOperand(operand: Expression): UnaryExpression; - function parenthesizeListElements(elements: NodeArray): NodeArray; - function parenthesizeExpressionForList(expression: Expression): Expression; - function parenthesizeExpressionForExpressionStatement(expression: Expression): Expression; - function parenthesizeConditionalTypeMember(member: TypeNode): TypeNode; - function parenthesizeElementTypeMember(member: TypeNode): TypeNode; - function parenthesizeArrayTypeMember(member: TypeNode): TypeNode; - function parenthesizeElementTypeMembers(members: ReadonlyArray): NodeArray; - function parenthesizeTypeParameters(typeParameters: ReadonlyArray | undefined): MutableNodeArray | undefined; - function parenthesizeConciseBody(body: ConciseBody): ConciseBody; - function isCommaSequence(node: Expression): node is (BinaryExpression & { - operatorToken: Token; - }) | CommaListExpression; - enum OuterExpressionKinds { - Parentheses = 1, - Assertions = 2, - PartiallyEmittedExpressions = 4, - All = 7 - } - type OuterExpression = ParenthesizedExpression | TypeAssertion | AsExpression | NonNullExpression | PartiallyEmittedExpression; - function isOuterExpression(node: Node, kinds?: OuterExpressionKinds): node is OuterExpression; - function skipOuterExpressions(node: Expression, kinds?: OuterExpressionKinds): Expression; - function skipOuterExpressions(node: Node, kinds?: OuterExpressionKinds): Node; - function skipAssertions(node: Expression): Expression; - function skipAssertions(node: Node): Node; - function recreateOuterExpressions(outerExpression: Expression | undefined, innerExpression: Expression, kinds?: OuterExpressionKinds): Expression; - function startOnNewLine(node: T): T; - function getExternalHelpersModuleName(node: SourceFile): Identifier | undefined; - function getOrCreateExternalHelpersModuleNameIfNeeded(node: SourceFile, compilerOptions: CompilerOptions, hasExportStarsToExportValues?: boolean, hasImportStarOrImportDefault?: boolean): Identifier | undefined; - /** - * Get the name of that target module from an import or export declaration - */ - function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile): Identifier | undefined; - /** - * Get the name of a target module from an import/export declaration as should be written in the emitted output. - * The emitted output name can be different from the input if: - * 1. The module has a /// - * 2. --out or --outFile is used, making the name relative to the rootDir - * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). - * Otherwise, a new StringLiteral node representing the module name will be returned. - */ - function getExternalModuleNameLiteral(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions): StringLiteral | undefined; - /** - * Get the name of a module as should be written in the emitted output. - * The emitted output name can be different from the input if: - * 1. The module has a /// - * 2. --out or --outFile is used, making the name relative to the rootDir - * Otherwise, a new StringLiteral node representing the module name will be returned. - */ - function tryGetModuleNameFromFile(file: SourceFile | undefined, host: EmitHost, options: CompilerOptions): StringLiteral | undefined; - /** - * Gets the initializer of an BindingOrAssignmentElement. - */ - function getInitializerOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): Expression | undefined; - /** - * Gets the name of an BindingOrAssignmentElement. - */ - function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementTarget | undefined; - /** - * Determines whether an BindingOrAssignmentElement is a rest element. - */ - function getRestIndicatorOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementRestIndicator | undefined; - /** - * Gets the property name of a BindingOrAssignmentElement - */ - function getPropertyNameOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | undefined; - /** - * Gets the elements of a BindingOrAssignmentPattern - */ - function getElementsOfBindingOrAssignmentPattern(name: BindingOrAssignmentPattern): ReadonlyArray; - function convertToArrayAssignmentElement(element: BindingOrAssignmentElement): Expression; - function convertToObjectAssignmentElement(element: BindingOrAssignmentElement): ObjectLiteralElementLike; - function convertToAssignmentPattern(node: BindingOrAssignmentPattern): AssignmentPattern; - function convertToObjectAssignmentPattern(node: ObjectBindingOrAssignmentPattern): ObjectLiteralExpression; - function convertToArrayAssignmentPattern(node: ArrayBindingOrAssignmentPattern): ArrayLiteralExpression; - function convertToAssignmentElementTarget(node: BindingOrAssignmentElementTarget): Expression; -} declare namespace ts { /** * Visits a Node using the supplied visitor, possibly returning a new Node in its place. @@ -8535,402 +4128,11 @@ declare namespace ts { function visitEachChild(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined; } declare namespace ts { - /** - * Similar to `reduceLeft`, performs a reduction against each child of a node. - * NOTE: Unlike `forEachChild`, this does *not* visit every node. - * - * @param node The node containing the children to reduce. - * @param initial The initial value to supply to the reduction. - * @param f The callback function - */ - function reduceEachChild(node: Node | undefined, initial: T, cbNode: (memo: T, node: Node) => T, cbNodeArray?: (memo: T, nodes: NodeArray) => T): T; - /** - * Merges generated lexical declarations into a new statement list. - */ - function mergeLexicalEnvironment(statements: NodeArray, declarations: ReadonlyArray | undefined): NodeArray; - /** - * Appends generated lexical declarations to an array of statements. - */ - function mergeLexicalEnvironment(statements: Statement[], declarations: ReadonlyArray | undefined): Statement[]; - /** - * Lifts a NodeArray containing only Statement nodes to a block. - * - * @param nodes The NodeArray. - */ - function liftToBlock(nodes: ReadonlyArray): Statement; - /** - * Aggregates the TransformFlags for a Node and its subtree. - */ - function aggregateTransformFlags(node: T): T; - namespace Debug { - function failBadSyntaxKind(node: Node, message?: string): never; - const assertEachNode: (nodes: Node[], test: (node: Node) => boolean, message?: string | undefined) => void; - const assertNode: (node: Node | undefined, test: ((node: Node | undefined) => boolean) | undefined, message?: string | undefined) => void; - const assertOptionalNode: (node: Node, test: (node: Node) => boolean, message?: string | undefined) => void; - const assertOptionalToken: (node: Node, kind: SyntaxKind, message?: string | undefined) => void; - const assertMissingNode: typeof noop; - /** - * Injects debug information into frequently used types. - */ - function enableDebugInfo(): void; - } -} -declare namespace ts { - interface SourceFileLikeCache { - get(path: Path): SourceFileLike | undefined; - } - function createSourceFileLikeCache(host: { - readFile?: (path: string) => string | undefined; - fileExists?: (path: string) => boolean; - }): SourceFileLikeCache; -} -declare namespace ts.sourcemaps { - interface SourceMapData { - version?: number; - file?: string; - sourceRoot?: string; - sources: string[]; - sourcesContent?: (string | null)[]; - names?: string[]; - mappings: string; - } - interface SourceMappableLocation { - fileName: string; - position: number; - } - interface SourceMapper { - getOriginalPosition(input: SourceMappableLocation): SourceMappableLocation; - getGeneratedPosition(input: SourceMappableLocation): SourceMappableLocation; - } - const identitySourceMapper: { - getOriginalPosition: typeof identity; - getGeneratedPosition: typeof identity; - }; - interface SourceMapDecodeHost { - readFile(path: string): string | undefined; - fileExists(path: string): boolean; - getCanonicalFileName(path: string): string; - log(text: string): void; - } - function decode(host: SourceMapDecodeHost, mapPath: string, map: SourceMapData, program?: Program, fallbackCache?: SourceFileLikeCache): SourceMapper; - interface MappingsDecoder extends Iterator { - readonly decodingIndex: number; - readonly error: string | undefined; - readonly lastSpan: SourceMapSpan; - } - function decodeMappings(map: SourceMapData): MappingsDecoder; -} -declare namespace ts { - function getOriginalNodeId(node: Node): number; - interface ExternalModuleInfo { - externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; - externalHelpersImportDeclaration: ImportDeclaration | undefined; - exportSpecifiers: Map; - exportedBindings: Identifier[][]; - exportedNames: Identifier[] | undefined; - exportEquals: ExportAssignment | undefined; - hasExportStarsToExportValues: boolean; - } - function chainBundle(transformSourceFile: (x: SourceFile) => SourceFile): (x: SourceFile | Bundle) => SourceFile | Bundle; - function getImportNeedsImportStarHelper(node: ImportDeclaration): boolean; - function getImportNeedsImportDefaultHelper(node: ImportDeclaration): boolean; - function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver, compilerOptions: CompilerOptions): ExternalModuleInfo; - /** - * Used in the module transformer to check if an expression is reasonably without sideeffect, - * and thus better to copy into multiple places rather than to cache in a temporary variable - * - this is mostly subjective beyond the requirement that the expression not be sideeffecting - */ - function isSimpleCopiableExpression(expression: Expression): boolean; - /** - * @param input Template string input strings - * @param args Names which need to be made file-level unique - */ - function helperString(input: TemplateStringsArray, ...args: string[]): (uniqueName: EmitHelperUniqueNameCallback) => string; -} -declare namespace ts { - enum FlattenLevel { - All = 0, - ObjectRest = 1 - } - /** - * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. - * - * @param node The node to flatten. - * @param visitor An optional visitor used to visit initializers. - * @param context The transformation context. - * @param level Indicates the extent to which flattening should occur. - * @param needsValue An optional value indicating whether the value from the right-hand-side of - * the destructuring assignment is needed as part of a larger expression. - * @param createAssignmentCallback An optional callback used to create the assignment expression. - */ - function flattenDestructuringAssignment(node: VariableDeclaration | DestructuringAssignment, visitor: ((node: Node) => VisitResult) | undefined, context: TransformationContext, level: FlattenLevel, needsValue?: boolean, createAssignmentCallback?: (name: Identifier, value: Expression, location?: TextRange) => Expression): Expression; - /** - * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. - * - * @param node The node to flatten. - * @param visitor An optional visitor used to visit initializers. - * @param context The transformation context. - * @param boundValue The value bound to the declaration. - * @param skipInitializer A value indicating whether to ignore the initializer of `node`. - * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line. - * @param level Indicates the extent to which flattening should occur. - */ - function flattenDestructuringBinding(node: VariableDeclaration | ParameterDeclaration, visitor: (node: Node) => VisitResult, context: TransformationContext, level: FlattenLevel, rval?: Expression, hoistTempVariables?: boolean, skipInitializer?: boolean): VariableDeclaration[]; -} -declare namespace ts { - function transformTypeScript(context: TransformationContext): (node: SourceFile | Bundle) => SourceFile | Bundle; -} -declare namespace ts { - function transformES2017(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; - const asyncSuperHelper: EmitHelper; - const advancedAsyncSuperHelper: EmitHelper; -} -declare namespace ts { - function transformESNext(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; - function createAssignHelper(context: TransformationContext, attributesSegments: Expression[]): CallExpression; -} -declare namespace ts { - function transformJsx(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; -} -declare namespace ts { - function transformES2016(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; -} -declare namespace ts { - function transformES2015(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; -} -declare namespace ts { - /** - * Transforms ES5 syntax into ES3 syntax. - * - * @param context Context and state information for the transformation. - */ - function transformES5(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; -} -declare namespace ts { - function transformGenerators(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; -} -declare namespace ts { - function transformModule(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; -} -declare namespace ts { - function transformSystemModule(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; -} -declare namespace ts { - function transformES2015Module(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle; -} -declare namespace ts { - type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => (SymbolAccessibilityDiagnostic | undefined); - interface SymbolAccessibilityDiagnostic { - errorNode: Node; - diagnosticMessage: DiagnosticMessage; - typeName?: DeclarationName | QualifiedName; - } - type DeclarationDiagnosticProducing = VariableDeclaration | PropertyDeclaration | PropertySignature | BindingElement | SetAccessorDeclaration | GetAccessorDeclaration | ConstructSignatureDeclaration | CallSignatureDeclaration | MethodDeclaration | MethodSignature | FunctionDeclaration | ParameterDeclaration | TypeParameterDeclaration | ExpressionWithTypeArguments | ImportEqualsDeclaration | TypeAliasDeclaration | ConstructorDeclaration | IndexSignatureDeclaration; - function canProduceDiagnostics(node: Node): node is DeclarationDiagnosticProducing; - function createGetSymbolAccessibilityDiagnosticForNodeName(node: DeclarationDiagnosticProducing): (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic | undefined; - function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationDiagnosticProducing): (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic | undefined; -} -declare namespace ts { - function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, file: SourceFile | undefined): DiagnosticWithLocation[] | undefined; - /** - * Transforms a ts file into a .d.ts file - * This process requires type information, which is retrieved through the emit resolver. Because of this, - * in many places this transformer assumes it will be operating on parse tree nodes directly. - * This means that _no transforms should be allowed to occur before this one_. - */ - function transformDeclarations(context: TransformationContext): { - (node: Bundle): Bundle; - (node: SourceFile): SourceFile; - (node: SourceFile | Bundle): SourceFile | Bundle; - }; -} -declare namespace ts { - function getTransformers(compilerOptions: CompilerOptions, customTransformers?: CustomTransformers): TransformerFactory[]; - /** - * Transforms an array of SourceFiles by passing them through each transformer. - * - * @param resolver The emit resolver provided by the checker. - * @param host The emit host object used to interact with the file system. - * @param options Compiler options to surface in the `TransformationContext`. - * @param nodes An array of nodes to transform. - * @param transforms An array of `TransformerFactory` callbacks. - * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. - */ - function transformNodes(resolver: EmitResolver | undefined, host: EmitHost | undefined, options: CompilerOptions, nodes: ReadonlyArray, transformers: ReadonlyArray>, allowDtsFiles: boolean): TransformationResult; -} -declare namespace ts { - interface SourceMapWriter { - /** - * Initialize the SourceMapWriter for a new output file. - * - * @param filePath The path to the generated output file. - * @param sourceMapFilePath The path to the output source map file. - * @param sourceFileOrBundle The input source file or bundle for the program. - */ - initialize(filePath: string, sourceMapFilePath: string | undefined, sourceFileOrBundle: SourceFile | Bundle, sourceMapOutput?: SourceMapData[]): void; - /** - * Reset the SourceMapWriter to an empty state. - */ - reset(): void; - /** - * Set the current source file. - * - * @param sourceFile The source file. - */ - setSourceFile(sourceFile: SourceMapSource): void; - /** - * Emits a mapping. - * - * If the position is synthetic (undefined or a negative value), no mapping will be - * created. - * - * @param pos The position. - */ - emitPos(pos: number): void; - /** - * Emits a node with possible leading and trailing source maps. - * - * @param hint The current emit context - * @param node The node to emit. - * @param emitCallback The callback used to emit the node. - */ - emitNodeWithSourceMap(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; - /** - * Emits a token of a node node with possible leading and trailing source maps. - * - * @param node The node containing the token. - * @param token The token to emit. - * @param tokenStartPos The start pos of the token. - * @param emitCallback The callback used to emit the token. - */ - emitTokenWithSourceMap(node: Node, token: SyntaxKind, writer: (s: string) => void, tokenStartPos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, tokenStartPos: number) => number): number; - /** - * Gets the text for the source map. - */ - getText(): string; - /** - * Gets the SourceMappingURL for the source map. - */ - getSourceMappingURL(): string; - } - interface SourceMapOptions { - sourceMap?: boolean; - inlineSourceMap?: boolean; - inlineSources?: boolean; - sourceRoot?: string; - mapRoot?: string; - extendedDiagnostics?: boolean; - } - function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter, compilerOptions?: SourceMapOptions): SourceMapWriter; -} -declare namespace ts { - interface CommentWriter { - reset(): void; - setSourceFile(sourceFile: SourceFile): void; - setWriter(writer: EmitTextWriter | undefined): void; - emitNodeWithComments(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node) => void): void; - emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void; - emitTrailingCommentsOfPosition(pos: number, prefixSpace?: boolean): void; - emitLeadingCommentsOfPosition(pos: number): void; - } - function createCommentWriter(printerOptions: PrinterOptions, emitPos: ((pos: number) => void) | undefined): CommentWriter; -} -declare namespace ts { - /** - * Iterates over the source files that are expected to have an emit output. - * - * @param host An EmitHost. - * @param action The action to execute. - * @param sourceFilesOrTargetSourceFile - * If an array, the full list of source files to emit. - * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. - */ - function forEachEmittedFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) => T, sourceFilesOrTargetSourceFile?: ReadonlyArray | SourceFile, emitOnlyDtsFiles?: boolean): T | undefined; - function getOutputPathsFor(sourceFile: SourceFile | Bundle, host: EmitHost, forceDtsPaths: boolean): EmitFileNames; - function getOutputExtension(sourceFile: SourceFile, options: CompilerOptions): Extension; - function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean, transformers?: TransformerFactory[], declarationTransformers?: TransformerFactory[]): EmitResult; function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } -declare namespace ts { - /** - * Partial interface of the System thats needed to support the caching of directory structure - */ - interface DirectoryStructureHost { - fileExists(path: string): boolean; - readFile(path: string, encoding?: string): string | undefined; - directoryExists?(path: string): boolean; - getDirectories?(path: string): string[]; - readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - createDirectory?(path: string): void; - writeFile?(path: string, data: string, writeByteOrderMark?: boolean): void; - } - interface FileAndDirectoryExistence { - fileExists: boolean; - directoryExists: boolean; - } - interface CachedDirectoryStructureHost extends DirectoryStructureHost { - useCaseSensitiveFileNames: boolean; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - /** Returns the queried result for the file exists and directory exists if at all it was done */ - addOrDeleteFileOrDirectory(fileOrDirectory: string, fileOrDirectoryPath: Path): FileAndDirectoryExistence | undefined; - addOrDeleteFile(fileName: string, filePath: Path, eventKind: FileWatcherEventKind): void; - clearCache(): void; - } - function createCachedDirectoryStructureHost(host: DirectoryStructureHost, currentDirectory: string, useCaseSensitiveFileNames: boolean): CachedDirectoryStructureHost | undefined; - enum ConfigFileProgramReloadLevel { - None = 0, - /** Update the file name list from the disk */ - Partial = 1, - /** Reload completely by re-reading contents of config file from disk and updating program */ - Full = 2 - } - /** - * Updates the existing missing file watches with the new set of missing files after new program is created - */ - function updateMissingFilePathsWatch(program: Program, missingFileWatches: Map, createMissingFileWatch: (missingFilePath: Path) => FileWatcher): void; - interface WildcardDirectoryWatcher { - watcher: FileWatcher; - flags: WatchDirectoryFlags; - } - /** - * Updates the existing wild card directory watches with the new set of wild card directories from the config file - * after new program is created because the config file was reloaded or program was created first time from the config file - * Note that there is no need to call this function when the program is updated with additional files without reloading config files, - * as wildcard directories wont change unless reloading config file - */ - function updateWatchingWildcardDirectories(existingWatchedForWildcards: Map, wildcardDirectories: Map, watchDirectory: (directory: string, flags: WatchDirectoryFlags) => FileWatcher): void; - function isEmittedFileOfProgram(program: Program | undefined, file: string): boolean; - enum WatchLogLevel { - None = 0, - TriggerOnly = 1, - Verbose = 2 - } - interface WatchFileHost { - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - } - interface WatchDirectoryHost { - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - } - type WatchFile = (host: WatchFileHost, file: string, callback: FileWatcherCallback, pollingInterval: PollingInterval, detailInfo1?: X, detailInfo2?: Y) => FileWatcher; - type FilePathWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind, filePath: Path) => void; - type WatchFilePath = (host: WatchFileHost, file: string, callback: FilePathWatcherCallback, pollingInterval: PollingInterval, path: Path, detailInfo1?: X, detailInfo2?: Y) => FileWatcher; - type WatchDirectory = (host: WatchDirectoryHost, directory: string, callback: DirectoryWatcherCallback, flags: WatchDirectoryFlags, detailInfo1?: X, detailInfo2?: Y) => FileWatcher; - interface WatchFactory { - watchFile: WatchFile; - watchFilePath: WatchFilePath; - watchDirectory: WatchDirectory; - } - function getWatchFactory(watchLogLevel: WatchLogLevel, log: (s: string) => void, getDetailWatchInfo?: GetDetailWatchInfo): WatchFactory; - type GetDetailWatchInfo = (detailInfo1: X, detailInfo2: Y | undefined) => string; - function closeFileWatcherOf(objWithWatcher: T): void; -} declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; - function computeCommonSourceDirectoryOfFilenames(fileNames: string[], currentDirectory: string, getCanonicalFileName: GetCanonicalFileName): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; interface FormatDiagnosticsHost { @@ -8940,23 +4142,8 @@ declare namespace ts { } function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; - /** @internal */ - enum ForegroundColorEscapeSequences { - Grey = "\u001B[90m", - Red = "\u001B[91m", - Yellow = "\u001B[93m", - Blue = "\u001B[94m", - Cyan = "\u001B[96m" - } - /** @internal */ - function formatColorAndReset(text: string, formatStyle: string): string; - function formatLocation(file: SourceFile, start: number, host: FormatDiagnosticsHost, color?: typeof formatColorAndReset): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string; - /** - * Determines if program structure is upto date or needs to be recreated - */ - function isProgramUptoDate(program: Program | undefined, rootFileNames: string[], newOptions: CompilerOptions, getSourceVersion: (path: Path) => string | undefined, fileExists: (fileName: string) => boolean, hasInvalidatedResolution: HasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: boolean): boolean; function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' @@ -8984,17 +4171,14 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - function parseConfigHostFromCompilerHost(host: CompilerHost): ParseConfigFileHost; - /** - * Returns the target config filename of a project reference - */ - function resolveProjectReferencePath(host: CompilerHost | UpToDateHost, ref: ProjectReference): ResolvedConfigFileName; + interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } /** - * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. - * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. - * This returns a diagnostic even if the module will be an untyped module. + * Returns the target config filename of a project reference. + * Note: The file might not exist. */ - function getResolutionDiagnostic(options: CompilerOptions, { extension }: ResolvedModuleFull): DiagnosticMessage | undefined; + function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -9007,126 +4191,6 @@ declare namespace ts { text: string; } } -declare namespace ts { - function getFileEmitOutput(program: Program, sourceFile: SourceFile, emitOnlyDtsFiles: boolean, cancellationToken?: CancellationToken, customTransformers?: CustomTransformers): EmitOutput; - interface BuilderState { - /** - * Information of the file eg. its version, signature etc - */ - fileInfos: Map; - /** - * Contains the map of ReferencedSet=Referenced files of the file if module emit is enabled - * Otherwise undefined - * Thus non undefined value indicates, module emit - */ - readonly referencedMap: ReadonlyMap | undefined; - /** - * Map of files that have already called update signature. - * That means hence forth these files are assumed to have - * no change in their signature for this version of the program - */ - hasCalledUpdateShapeSignature: Map; - /** - * Cache of all files excluding default library file for the current program - */ - allFilesExcludingDefaultLibraryFile: ReadonlyArray | undefined; - /** - * Cache of all the file names - */ - allFileNames: ReadonlyArray | undefined; - } -} -declare namespace ts.BuilderState { - /** - * Information about the source file: Its version and optional signature from last emit - */ - interface FileInfo { - readonly version: string; - signature: string | undefined; - } - /** - * Referenced files with values for the keys as referenced file's path to be true - */ - type ReferencedSet = ReadonlyMap; - /** - * Compute the hash to store the shape of the file - */ - type ComputeHash = (data: string) => string; - /** - * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed - */ - function canReuseOldState(newReferencedMap: ReadonlyMap | undefined, oldState: Readonly | undefined): boolean | undefined; - /** - * Creates the state of file references and signature for the new program from oldState if it is safe - */ - function create(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly): BuilderState; - /** - * Gets the files affected by the path from the program - */ - function getFilesAffectedBy(state: BuilderState, programOfThisState: Program, path: Path, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash, cacheToUpdateSignature?: Map): ReadonlyArray; - /** - * Updates the signatures from the cache into state's fileinfo signatures - * This should be called whenever it is safe to commit the state of the builder - */ - function updateSignaturesFromCache(state: BuilderState, signatureCache: Map): void; - /** - * Get all the dependencies of the sourceFile - */ - function getAllDependencies(state: BuilderState, programOfThisState: Program, sourceFile: SourceFile): ReadonlyArray; -} -declare namespace ts { - /** - * State to store the changed files, affected files and cache semantic diagnostics - */ - interface BuilderProgramState extends BuilderState { - /** - * Cache of semantic diagnostics for files with their Path being the key - */ - semanticDiagnosticsPerFile: Map> | undefined; - /** - * The map has key by source file's path that has been changed - */ - changedFilesSet: Map; - /** - * Set of affected files being iterated - */ - affectedFiles: ReadonlyArray | undefined; - /** - * Current index to retrieve affected file from - */ - affectedFilesIndex: number | undefined; - /** - * Current changed file for iterating over affected files - */ - currentChangedFilePath: Path | undefined; - /** - * Map of file signatures, with key being file path, calculated while getting current changed file's affected files - * These will be commited whenever the iteration through affected files of current changed file is complete - */ - currentAffectedFilesSignatures: Map | undefined; - /** - * Already seen affected files - */ - seenAffectedFiles: Map | undefined; - /** - * program corresponding to this state - */ - program: Program; - } - enum BuilderProgramKind { - SemanticDiagnosticsBuilderProgram = 0, - EmitAndSemanticDiagnosticsBuilderProgram = 1 - } - interface BuilderCreationParameters { - newProgram: Program; - host: BuilderProgramHost; - oldProgram: BuilderProgram | undefined; - configFileParsingDiagnostics: ReadonlyArray; - } - function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderCreationParameters; - function createBuilderProgram(kind: BuilderProgramKind.SemanticDiagnosticsBuilderProgram, builderCreationParameters: BuilderCreationParameters): SemanticDiagnosticsBuilderProgram; - function createBuilderProgram(kind: BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, builderCreationParameters: BuilderCreationParameters): EmitAndSemanticDiagnosticsBuilderProgram; -} declare namespace ts { type AffectedFileResult = { result: T; @@ -9151,7 +4215,6 @@ declare namespace ts { * Builder to manage the program state changes */ interface BuilderProgram { - getState(): BuilderProgramState; /** * Returns current program */ @@ -9253,99 +4316,6 @@ declare namespace ts { function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; } -declare namespace ts { - /** This is the cache of module/typedirectives resolution that can be retained across program */ - interface ResolutionCache { - startRecordingFilesWithChangedResolutions(): void; - finishRecordingFilesWithChangedResolutions(): Path[] | undefined; - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined): ResolvedModuleFull[]; - getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): CachedResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - invalidateResolutionOfFile(filePath: Path): void; - removeResolutionsOfFile(filePath: Path): void; - setFilesWithInvalidatedNonRelativeUnresolvedImports(filesWithUnresolvedImports: Map>): void; - createHasInvalidatedResolution(forceAllFilesAsInvalidated?: boolean): HasInvalidatedResolution; - startCachingPerDirectoryResolution(): void; - finishCachingPerDirectoryResolution(): void; - updateTypeRootsWatch(): void; - closeTypeRootsWatch(): void; - clear(): void; - } - interface ResolutionWithFailedLookupLocations { - readonly failedLookupLocations: ReadonlyArray; - isInvalidated?: boolean; - refCount?: number; - } - interface CachedResolvedModuleWithFailedLookupLocations extends ResolvedModuleWithFailedLookupLocations, ResolutionWithFailedLookupLocations { - } - interface ResolutionCacheHost extends ModuleResolutionHost { - toPath(fileName: string): Path; - getCanonicalFileName: GetCanonicalFileName; - getCompilationSettings(): CompilerOptions; - watchDirectoryOfFailedLookupLocation(directory: string, cb: DirectoryWatcherCallback, flags: WatchDirectoryFlags): FileWatcher; - onInvalidatedResolution(): void; - watchTypeRootsDirectory(directory: string, cb: DirectoryWatcherCallback, flags: WatchDirectoryFlags): FileWatcher; - onChangedAutomaticTypeDirectiveNames(): void; - getCachedDirectoryStructureHost(): CachedDirectoryStructureHost | undefined; - projectName?: string; - getGlobalCache?(): string | undefined; - writeLog(s: string): void; - maxNumberOfFilesToIterateForInvalidation?: number; - getCurrentProgram(): Program; - } - const maxNumberOfFilesToIterateForInvalidation = 256; - function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string | undefined, logChangesWhenResolvingModule: boolean): ResolutionCache; -} -declare namespace ts.moduleSpecifiers { - interface ModuleSpecifierPreferences { - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - } - function getModuleSpecifier(compilerOptions: CompilerOptions, importingSourceFile: SourceFile, importingSourceFileName: Path, toFileName: string, host: ModuleSpecifierResolutionHost, files: ReadonlyArray, preferences?: ModuleSpecifierPreferences): string; - function getModuleSpecifiers(moduleSymbol: Symbol, compilerOptions: CompilerOptions, importingSourceFile: SourceFile, host: ModuleSpecifierResolutionHost, files: ReadonlyArray, preferences: ModuleSpecifierPreferences): ReadonlyArray>; -} -declare namespace ts { - /** - * Create a function that reports error by writing to the system and handles the formating of the diagnostic - */ - function createDiagnosticReporter(system: System, pretty?: boolean): DiagnosticReporter; - /** @internal */ - const nonClearingMessageCodes: number[]; - /** @internal */ - const screenStartingMessageCodes: number[]; - /** - * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic - */ - function createWatchStatusReporter(system: System, pretty?: boolean): WatchStatusReporter; - /** Parses config file using System interface */ - function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, system: System, reportDiagnostic: DiagnosticReporter): ParsedCommandLine | undefined; - /** - * Program structure needed to emit the files and report diagnostics - */ - interface ProgramToEmitFilesAndReportErrors { - getCurrentDirectory(): string; - getCompilerOptions(): CompilerOptions; - getSourceFiles(): ReadonlyArray; - getSyntacticDiagnostics(): ReadonlyArray; - getOptionsDiagnostics(): ReadonlyArray; - getGlobalDiagnostics(): ReadonlyArray; - getSemanticDiagnostics(): ReadonlyArray; - getConfigFileParsingDiagnostics(): ReadonlyArray; - emit(): EmitResult; - } - type ReportEmitErrorSummary = (errorCount: number) => void; - /** - * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options - */ - function emitFilesAndReportErrors(program: ProgramToEmitFilesAndReportErrors, reportDiagnostic: DiagnosticReporter, writeFileName?: (s: string) => void, reportSummary?: ReportEmitErrorSummary): ExitStatus; - /** - * Creates the watch compiler host from system for config file in watch mode - */ - function createWatchCompilerHostOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; - /** - * Creates the watch compiler host from system for compiling root files and options in watch mode - */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; -} declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ @@ -9359,7 +4329,6 @@ declare namespace ts { afterProgramCreate?(program: T): void; /** If provided, called with Diagnostic message that informs about change in watch status */ onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; - maxNumberOfFilesToIterateForInvalidation?: number; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -9401,12 +4370,6 @@ declare namespace ts { /** If provided, will be used to reset existing delayed compilation */ clearTimeout?(timeoutId: any): void; } - /** Internal interface used to wire emit through same host */ - interface WatchCompilerHost { - createDirectory?(path: string): void; - writeFile?(path: string, data: string, writeByteOrderMark?: boolean): void; - onCachedDirectoryStructureHostCreate?(host: CachedDirectoryStructureHost): void; - } /** * Host to create watch with root files and options */ @@ -9430,18 +4393,9 @@ declare namespace ts { */ readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; } - /** - * Host to create watch with config file that is already parsed (from tsc) - */ - interface WatchCompilerHostOfConfigFile extends WatchCompilerHost { - optionsToExtend?: CompilerOptions; - configFileParsingResult?: ParsedCommandLine; - } interface Watch { /** Synchronize with host and get updated program */ getProgram(): T; - /** Gets the existing program without synchronizing with changes on host */ - getCurrentProgram(): T; } /** * Creates the watch what generates program using the config file @@ -9643,31 +4597,6 @@ declare namespace ts { function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; } -//# sourceMappingURL=compiler.d.ts.map -declare namespace ts.server { - const ActionSet: ActionSet; - const ActionInvalidate: ActionInvalidate; - const ActionPackageInstalled: ActionPackageInstalled; - const EventTypesRegistry: EventTypesRegistry; - const EventBeginInstallTypes: EventBeginInstallTypes; - const EventEndInstallTypes: EventEndInstallTypes; - const EventInitializationFailed: EventInitializationFailed; - namespace Arguments { - const GlobalCacheLocation = "--globalTypingsCacheLocation"; - const LogFile = "--logFile"; - const EnableTelemetry = "--enableTelemetry"; - const TypingSafeListLocation = "--typingSafeListLocation"; - const TypesMapLocation = "--typesMapLocation"; - /** - * This argument specifies the location of the NPM executable. - * typingsInstaller will run the command with `${npmLocation} install ...`. - */ - const NpmLocation = "--npmLocation"; - } - function hasArgument(argumentName: string): boolean; - function findArgument(argumentName: string): string | undefined; - function nowString(): string; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; @@ -9685,7 +4614,6 @@ declare namespace ts.server { interface TypingInstallerRequestWithProjectName { readonly projectName: string; } - type TypingInstallerRequestUnion = DiscoverTypings | CloseProject | TypesRegistryRequest | InstallPackageRequest; interface DiscoverTypings extends TypingInstallerRequestWithProjectName { readonly fileNames: string[]; readonly projectRootPath: Path; @@ -9707,10 +4635,6 @@ declare namespace ts.server { readonly packageName: string; readonly projectRootPath: Path; } - interface TypesRegistryResponse extends TypingInstallerResponse { - readonly kind: EventTypesRegistry; - readonly typesRegistry: MapLike>; - } interface PackageInstalledResponse extends ProjectResponse { readonly kind: ActionPackageInstalled; readonly success: boolean; @@ -9739,13 +4663,6 @@ declare namespace ts.server { readonly kind: EventEndInstallTypes; readonly installSuccess: boolean; } - interface InstallTypingHost extends JsTyping.TypingResolutionHost { - useCaseSensitiveFileNames: boolean; - writeFile(path: string, content: string): void; - createDirectory(path: string): void; - watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - } interface SetTypings extends ProjectResponse { readonly typeAcquisition: TypeAcquisition; readonly compilerOptions: CompilerOptions; @@ -9753,86 +4670,14 @@ declare namespace ts.server { readonly unresolvedImports: SortedReadonlyArray; readonly kind: ActionSet; } - type TypingInstallerResponseUnion = SetTypings | InvalidateCachedTypings | TypesRegistryResponse | PackageInstalledResponse | InstallTypes | InitializationFailedResponse; } -declare namespace ts.JsTyping { - interface TypingResolutionHost { - directoryExists(path: string): boolean; - fileExists(fileName: string): boolean; - readFile(path: string, encoding?: string): string | undefined; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray | undefined, depth?: number): string[]; - } - interface CachedTyping { - typingLocation: string; - version: Semver; - } - function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: MapLike): boolean; - const nodeCoreModuleList: ReadonlyArray; - const nodeCoreModules: Map; - /** - * A map of loose file names to library names that we are confident require typings - */ - type SafeList = ReadonlyMap; - function loadSafeList(host: TypingResolutionHost, safeListPath: Path): SafeList; - function loadTypesMap(host: TypingResolutionHost, typesMapPath: Path): SafeList | undefined; - /** - * @param host is the object providing I/O related operations. - * @param fileNames are the file names that belong to the same project - * @param projectRootPath is the path to the project root directory - * @param safeListPath is the path used to retrieve the safe list - * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions - * @param typeAcquisition is used to customize the typing acquisition process - * @param compilerOptions are used as a source for typing inference - */ - function discoverTypings(host: TypingResolutionHost, log: ((message: string) => void) | undefined, fileNames: string[], projectRootPath: Path, safeList: SafeList, packageNameToTypingLocation: ReadonlyMap, typeAcquisition: TypeAcquisition, unresolvedImports: ReadonlyArray, typesRegistry: ReadonlyMap>): { - cachedTypingPaths: string[]; - newTypingNames: string[]; - filesToWatch: string[]; - }; - enum PackageNameValidationResult { - Ok = 0, - ScopedPackagesNotSupported = 1, - EmptyName = 2, - NameTooLong = 3, - NameStartsWithDot = 4, - NameStartsWithUnderscore = 5, - NameContainsNonURISafeCharacters = 6 - } - /** - * Validates package name using rules defined at https://docs.npmjs.com/files/package.json - */ - function validatePackageName(packageName: string): PackageNameValidationResult; - function renderPackageNameValidationFailure(result: PackageNameValidationResult, typing: string): string; -} -declare namespace ts { - class Semver { - readonly major: number; - readonly minor: number; - readonly patch: number; - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - readonly isPrerelease: boolean; - static parse(semver: string): Semver; - static fromRaw({ major, minor, patch, isPrerelease }: Semver): Semver; - private static tryParse; - private constructor(); - readonly versionString: string; - equals(sem: Semver): boolean; - greaterThan(sem: Semver): boolean; - } -} -//# sourceMappingURL=jsTyping.d.ts.map declare namespace ts { interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; getChildAt(index: number, sourceFile?: SourceFile): Node; getChildren(sourceFile?: SourceFile): Node[]; - getChildren(sourceFile?: SourceFileLike): Node[]; getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; - getStart(sourceFile?: SourceFileLike, includeJsDocComment?: boolean): number; getFullStart(): number; getEnd(): number; getWidth(sourceFile?: SourceFileLike): number; @@ -9889,20 +4734,14 @@ declare namespace ts { getJsDocTags(): JSDocTagInfo[]; } interface SourceFile { - version: string; - scriptSnapshot: IScriptSnapshot | undefined; - nameTable: UnderscoreEscapedMap | undefined; - getNamedDeclarations(): Map>; getLineAndCharacterOfPosition(pos: number): LineAndCharacter; getLineEndOfPosition(pos: number): number; getLineStarts(): ReadonlyArray; getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; - sourceMapper?: sourcemaps.SourceMapper; } interface SourceFileLike { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - sourceMapper?: sourcemaps.SourceMapper; } interface SourceMapSource { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; @@ -9971,8 +4810,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - hasInvalidatedResolution?: HasInvalidatedResolution; - hasChangedAutomaticTypeDirectiveNames?: boolean; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. @@ -9989,7 +4826,6 @@ declare namespace ts { readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; } - const emptyOptions: {}; interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; @@ -10061,7 +4897,6 @@ declare namespace ts { getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program | undefined; - getNonBoundSourceFile(fileName: string): SourceFile; dispose(): void; } interface JsxClosingTagInfo { @@ -10213,9 +5048,6 @@ declare namespace ts { } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { - file: string; - type: "install package"; - packageName: string; } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. @@ -10727,285 +5559,8 @@ declare namespace ts { jsxAttributeStringLiteralValue = 24 } } -interface PromiseConstructor { - new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; - reject(reason: any): Promise; - all(values: (T | PromiseLike)[]): Promise; -} -declare var Promise: PromiseConstructor; -declare namespace ts { - const scanner: Scanner; - enum SemanticMeaning { - None = 0, - Value = 1, - Type = 2, - Namespace = 4, - All = 7 - } - function getMeaningFromDeclaration(node: Node): SemanticMeaning; - function getMeaningFromLocation(node: Node): SemanticMeaning; - function isInRightSideOfInternalImportEqualsDeclaration(node: Node): boolean; - function isCallExpressionTarget(node: Node): boolean; - function isNewExpressionTarget(node: Node): boolean; - function climbPastPropertyAccess(node: Node): Node; - function getTargetLabel(referenceNode: Node, labelName: string): Identifier | undefined; - function isJumpStatementTarget(node: Node): node is Identifier & { - parent: BreakOrContinueStatement; - }; - function isLabelOfLabeledStatement(node: Node): node is Identifier; - function isLabelName(node: Node): boolean; - function isRightSideOfQualifiedName(node: Node): boolean; - function isRightSideOfPropertyAccess(node: Node): boolean; - function isNameOfModuleDeclaration(node: Node): boolean; - function isNameOfFunctionDeclaration(node: Node): boolean; - function isLiteralNameOfPropertyDeclarationOrIndexAccess(node: StringLiteral | NumericLiteral): boolean; - function isExpressionOfExternalModuleImportEqualsDeclaration(node: Node): boolean; - function getContainerNode(node: Node): Declaration | undefined; - function getNodeKind(node: Node): ScriptElementKind; - function isThis(node: Node): boolean; - interface ListItemInfo { - listItemIndex: number; - list: Node; - } - function getLineStartPositionForPosition(position: number, sourceFile: SourceFileLike): number; - function rangeContainsRange(r1: TextRange, r2: TextRange): boolean; - function rangeContainsRangeExclusive(r1: TextRange, r2: TextRange): boolean; - function rangeContainsPosition(r: TextRange, pos: number): boolean; - function rangeContainsPositionExclusive(r: TextRange, pos: number): boolean; - function startEndContainsRange(start: number, end: number, range: TextRange): boolean; - function rangeContainsStartEnd(range: TextRange, start: number, end: number): boolean; - function rangeOverlapsWithStartEnd(r1: TextRange, start: number, end: number): boolean; - function nodeOverlapsWithStartEnd(node: Node, sourceFile: SourceFile, start: number, end: number): boolean; - function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number): boolean; - /** - * Assumes `candidate.start <= position` holds. - */ - function positionBelongsToNode(candidate: Node, position: number, sourceFile: SourceFile): boolean; - function findListItemInfo(node: Node): ListItemInfo | undefined; - function hasChildOfKind(n: Node, kind: SyntaxKind, sourceFile: SourceFile): boolean; - function findChildOfKind(n: Node, kind: T["kind"], sourceFile: SourceFileLike): T | undefined; - function findContainingList(node: Node): SyntaxList | undefined; - /** - * Gets the token whose text has range [start, end) and - * position >= start and (position < end or (position === end && token is literal or keyword or identifier)) - */ - function getTouchingPropertyName(sourceFile: SourceFile, position: number): Node; - /** - * Returns the token if position is in [start, end). - * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true - */ - function getTouchingToken(sourceFile: SourceFile, position: number, includePrecedingTokenAtEndPosition?: (n: Node) => boolean): Node; - /** Returns a token if position is in [start-of-leading-trivia, end) */ - function getTokenAtPosition(sourceFile: SourceFile, position: number): Node; - /** - * The token on the left of the position is the token that strictly includes the position - * or sits to the left of the cursor if it is on a boundary. For example - * - * fo|o -> will return foo - * foo |bar -> will return foo - * - */ - function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node | undefined; - function findNextToken(previousToken: Node, parent: Node, sourceFile: SourceFile): Node | undefined; - /** - * Finds the rightmost token satisfying `token.end <= position`, - * excluding `JsxText` tokens containing only whitespace. - */ - function findPrecedingToken(position: number, sourceFile: SourceFile, startNode?: Node, excludeJsdoc?: boolean): Node | undefined; - function isInString(sourceFile: SourceFile, position: number, previousToken?: Node | undefined): boolean; - /** - * returns true if the position is in between the open and close elements of an JSX expression. - */ - function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number): boolean; - function isInTemplateString(sourceFile: SourceFile, position: number): boolean; - function findPrecedingMatchingToken(token: Node, matchingTokenKind: SyntaxKind, sourceFile: SourceFile): Node | undefined; - interface PossibleTypeArgumentInfo { - readonly called: Identifier; - readonly nTypeArguments: number; - } - function isPossiblyTypeArgumentPosition(tokenIn: Node, sourceFile: SourceFile): PossibleTypeArgumentInfo | undefined; - /** - * Returns true if the cursor at position in sourceFile is within a comment. - * - * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) - * @param predicate Additional predicate to test on the comment range. - */ - function isInComment(sourceFile: SourceFile, position: number, tokenAtPosition?: Node): CommentRange | undefined; - function hasDocComment(sourceFile: SourceFile, position: number): boolean; - function getNodeModifiers(node: Node): string; - function getTypeArgumentOrTypeParameterList(node: Node): NodeArray | undefined; - function isComment(kind: SyntaxKind): boolean; - function isStringOrRegularExpressionOrTemplateLiteral(kind: SyntaxKind): boolean; - function isPunctuation(kind: SyntaxKind): boolean; - function isInsideTemplateLiteral(node: TemplateLiteralToken, position: number, sourceFile: SourceFile): boolean; - function isAccessibilityModifier(kind: SyntaxKind): boolean; - function cloneCompilerOptions(options: CompilerOptions): CompilerOptions; - function isArrayLiteralOrObjectLiteralDestructuringPattern(node: Node): boolean; - function isInReferenceComment(sourceFile: SourceFile, position: number): boolean; - function isInNonReferenceComment(sourceFile: SourceFile, position: number): boolean; - function createTextSpanFromNode(node: Node, sourceFile?: SourceFile): TextSpan; - function createTextSpanFromRange(range: TextRange): TextSpan; - function createTextRangeFromSpan(span: TextSpan): TextRange; - function createTextChangeFromStartLength(start: number, length: number, newText: string): TextChange; - function createTextChange(span: TextSpan, newText: string): TextChange; - const typeKeywords: ReadonlyArray; - function isTypeKeyword(kind: SyntaxKind): boolean; - /** True if the symbol is for an external module, as opposed to a namespace. */ - function isExternalModuleSymbol(moduleSymbol: Symbol): boolean; - /** Returns `true` the first time it encounters a node and `false` afterwards. */ - type NodeSeenTracker = (node: T) => boolean; - function nodeSeenTracker(): NodeSeenTracker; - function getSnapshotText(snap: IScriptSnapshot): string; - function repeatString(str: string, count: number): string; - function skipConstraint(type: Type): Type; - function getNameFromPropertyName(name: PropertyName): string | undefined; - function programContainsEs6Modules(program: Program): boolean; - function compilerOptionsIndicateEs6Modules(compilerOptions: CompilerOptions): boolean; - function hostUsesCaseSensitiveFileNames(host: LanguageServiceHost): boolean; - function hostGetCanonicalFileName(host: LanguageServiceHost): GetCanonicalFileName; - function makeImportIfNecessary(defaultImport: Identifier | undefined, namedImports: ReadonlyArray | undefined, moduleSpecifier: string, quotePreference: QuotePreference): ImportDeclaration | undefined; - function makeImport(defaultImport: Identifier | undefined, namedImports: ReadonlyArray | undefined, moduleSpecifier: string | Expression, quotePreference: QuotePreference): ImportDeclaration; - function makeStringLiteral(text: string, quotePreference: QuotePreference): StringLiteral; - enum QuotePreference { - Single = 0, - Double = 1 - } - function quotePreferenceFromString(str: StringLiteral, sourceFile: SourceFile): QuotePreference; - function getQuotePreference(sourceFile: SourceFile, preferences: UserPreferences): QuotePreference; - function symbolNameNoDefault(symbol: Symbol): string | undefined; - function symbolEscapedNameNoDefault(symbol: Symbol): __String | undefined; - function getPropertySymbolFromBindingElement(checker: TypeChecker, bindingElement: BindingElement & { - name: Identifier; - }): Symbol | undefined; - /** - * Find symbol of the given property-name and add the symbol to the given result array - * @param symbol a symbol to start searching for the given propertyName - * @param propertyName a name of property to search for - * @param result an array of symbol of found property symbols - * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. - * The value of previousIterationSymbol is undefined when the function is first called. - */ - function getPropertySymbolsFromBaseTypes(symbol: Symbol, propertyName: string, checker: TypeChecker, cb: (symbol: Symbol) => T | undefined): T | undefined; - function isMemberSymbolInBaseType(memberSymbol: Symbol, checker: TypeChecker): boolean; - interface ReadonlyNodeSet { - has(node: Node): boolean; - forEach(cb: (node: Node) => void): void; - some(pred: (node: Node) => boolean): boolean; - } - class NodeSet implements ReadonlyNodeSet { - private map; - add(node: Node): void; - has(node: Node): boolean; - forEach(cb: (node: Node) => void): void; - some(pred: (node: Node) => boolean): boolean; - } - interface ReadonlyNodeMap { - get(node: TNode): TValue | undefined; - has(node: TNode): boolean; - } - class NodeMap implements ReadonlyNodeMap { - private map; - get(node: TNode): TValue | undefined; - getOrUpdate(node: TNode, setValue: () => TValue): TValue; - set(node: TNode, value: TValue): void; - has(node: TNode): boolean; - forEach(cb: (value: TValue, node: TNode) => void): void; - } - function getParentNodeInSpan(node: Node | undefined, file: SourceFile, span: TextSpan): Node | undefined; - function findModifier(node: Node, kind: Modifier["kind"]): Modifier | undefined; - function insertImport(changes: textChanges.ChangeTracker, sourceFile: SourceFile, importDecl: Statement): void; -} -declare namespace ts { - function isFirstDeclarationOfSymbolParameter(symbol: Symbol): boolean; - function symbolPart(text: string, symbol: Symbol): SymbolDisplayPart; - function displayPart(text: string, kind: SymbolDisplayPartKind): SymbolDisplayPart; - function spacePart(): SymbolDisplayPart; - function keywordPart(kind: SyntaxKind): SymbolDisplayPart; - function punctuationPart(kind: SyntaxKind): SymbolDisplayPart; - function operatorPart(kind: SyntaxKind): SymbolDisplayPart; - function textOrKeywordPart(text: string): SymbolDisplayPart; - function textPart(text: string): SymbolDisplayPart; - /** - * The default is CRLF. - */ - function getNewLineOrDefaultFromHost(host: LanguageServiceHost | LanguageServiceShimHost, formatSettings?: FormatCodeSettings): string; - function lineBreakPart(): SymbolDisplayPart; - function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[]; - function typeToDisplayParts(typechecker: TypeChecker, type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[]; - function symbolToDisplayParts(typeChecker: TypeChecker, symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): SymbolDisplayPart[]; - function signatureToDisplayParts(typechecker: TypeChecker, signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[]; - function isImportOrExportSpecifierName(location: Node): location is Identifier; - /** - * Strip off existed single quotes or double quotes from a given string - * - * @return non-quoted string - */ - function stripQuotes(name: string): string; - function startsWithQuote(name: string): boolean; - function scriptKindIs(fileName: string, host: LanguageServiceHost, ...scriptKinds: ScriptKind[]): boolean; - function getScriptKind(fileName: string, host?: LanguageServiceHost): ScriptKind; - function getUniqueSymbolId(symbol: Symbol, checker: TypeChecker): number; - function getFirstNonSpaceCharacterPosition(text: string, position: number): number; - /** - * Creates a deep, memberwise clone of a node with no source map location. - * - * WARNING: This is an expensive operation and is only intended to be used in refactorings - * and code fixes (because those are triggered by explicit user actions). - */ - function getSynthesizedDeepClone(node: T, includeTrivia?: boolean): T; - function getSynthesizedDeepClones(nodes: NodeArray, includeTrivia?: boolean): NodeArray; - function getSynthesizedDeepClones(nodes: NodeArray | undefined, includeTrivia?: boolean): NodeArray | undefined; - /** - * Sets EmitFlags to suppress leading and trailing trivia on the node. - */ - function suppressLeadingAndTrailingTrivia(node: Node): void; - /** - * Sets EmitFlags to suppress leading trivia on the node. - */ - function suppressLeadingTrivia(node: Node): void; - /** - * Sets EmitFlags to suppress trailing trivia on the node. - */ - function suppressTrailingTrivia(node: Node): void; - function getUniqueName(baseName: string, sourceFile: SourceFile): string; - /** - * @return The index of the (only) reference to the extracted symbol. We want the cursor - * to be on the reference, rather than the declaration, because it's closer to where the - * user was before extracting it. - */ - function getRenameLocation(edits: ReadonlyArray, renameFilename: string, name: string, preferLastLocation: boolean): number; - function copyComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean): void; -} declare namespace ts { function createClassifier(): Classifier; - function getSemanticClassifications(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, classifiableNames: UnderscoreEscapedMap, span: TextSpan): ClassifiedSpan[]; - function getEncodedSemanticClassifications(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, classifiableNames: UnderscoreEscapedMap, span: TextSpan): Classifications; - function getSyntacticClassifications(cancellationToken: CancellationToken, sourceFile: SourceFile, span: TextSpan): ClassifiedSpan[]; - function getEncodedSyntacticClassifications(cancellationToken: CancellationToken, sourceFile: SourceFile, span: TextSpan): Classifications; -} -declare namespace ts.Completions.PathCompletions { - interface NameAndKind { - readonly name: string; - readonly kind: ScriptElementKind.scriptElement | ScriptElementKind.directory | ScriptElementKind.externalModuleName; - } - interface PathCompletion extends NameAndKind { - readonly span: TextSpan | undefined; - } - function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray; - function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): ReadonlyArray | undefined; -} -declare namespace ts.Completions { - type Log = (message: string) => void; - function getCompletionsAtPosition(host: LanguageServiceHost, program: Program, log: Log, sourceFile: SourceFile, position: number, preferences: UserPreferences, triggerCharacter: CompletionsTriggerCharacter | undefined): CompletionInfo | undefined; - interface CompletionEntryIdentifier { - name: string; - source?: string; - } - function getCompletionEntryDetails(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences, cancellationToken: CancellationToken): CompletionEntryDetails | undefined; - function getCompletionEntrySymbol(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier): Symbol | undefined; -} -declare namespace ts.DocumentHighlights { - function getDocumentHighlights(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: ReadonlyArray): DocumentHighlights[] | undefined; } declare namespace ts { /** @@ -11066,276 +5621,16 @@ declare namespace ts { */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; - getLanguageServiceRefCounts(path: Path): [string, number | undefined][]; reportStats(): string; } - interface ExternalDocumentCache { - setDocument(key: DocumentRegistryBucketKey, path: Path, sourceFile: SourceFile): void; - getDocument(key: DocumentRegistryBucketKey, path: Path): SourceFile | undefined; - } type DocumentRegistryBucketKey = string & { __bucketKey: any; }; function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; - function createDocumentRegistryInternal(useCaseSensitiveFileNames?: boolean, currentDirectory?: string, externalCache?: ExternalDocumentCache): DocumentRegistry; -} -declare namespace ts.FindAllReferences { - interface ImportsResult { - /** For every import of the symbol, the location and local symbol for the import. */ - importSearches: ReadonlyArray<[Identifier, Symbol]>; - /** For rename imports/exports `{ foo as bar }`, `foo` is not a local, so it may be added as a reference immediately without further searching. */ - singleReferences: ReadonlyArray; - /** List of source files that may (or may not) use the symbol via a namespace. (For UMD modules this is every file.) */ - indirectUsers: ReadonlyArray; - } - type ImportTracker = (exportSymbol: Symbol, exportInfo: ExportInfo, isForRename: boolean) => ImportsResult; - /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ - function createImportTracker(sourceFiles: ReadonlyArray, sourceFilesSet: ReadonlyMap, checker: TypeChecker, cancellationToken: CancellationToken | undefined): ImportTracker; - /** Info about an exported symbol to perform recursive search on. */ - interface ExportInfo { - exportingModuleSymbol: Symbol; - exportKind: ExportKind; - } - enum ExportKind { - Named = 0, - Default = 1, - ExportEquals = 2 - } - enum ImportExport { - Import = 0, - Export = 1 - } - type ModuleReference = { - kind: "import"; - literal: StringLiteralLike; - } - /** or */ - | { - kind: "reference"; - referencingFile: SourceFile; - ref: FileReference; - }; - function findModuleReferences(program: Program, sourceFiles: ReadonlyArray, searchModuleSymbol: Symbol): ModuleReference[]; - interface ImportedSymbol { - kind: ImportExport.Import; - symbol: Symbol; - isNamedImport: boolean; - } - interface ExportedSymbol { - kind: ImportExport.Export; - symbol: Symbol; - exportInfo: ExportInfo; - } - /** - * Given a local reference, we might notice that it's an import/export and recursively search for references of that. - * If at an import, look locally for the symbol it imports. - * If an an export, look for all imports of it. - * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`. - * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here. - */ - function getImportOrExportSymbol(node: Node, symbol: Symbol, checker: TypeChecker, comingFromExport: boolean): ImportedSymbol | ExportedSymbol | undefined; - function getExportInfo(exportSymbol: Symbol, exportKind: ExportKind, checker: TypeChecker): ExportInfo | undefined; -} -declare namespace ts.FindAllReferences { - interface SymbolAndEntries { - definition: Definition | undefined; - references: Entry[]; - } - type Definition = { - type: "symbol"; - symbol: Symbol; - } | { - type: "label"; - node: Identifier; - } | { - type: "keyword"; - node: Node; - } | { - type: "this"; - node: Node; - } | { - type: "string"; - node: StringLiteral; - }; - type Entry = NodeEntry | SpanEntry; - interface NodeEntry { - type: "node"; - node: Node; - isInString?: true; - } - interface SpanEntry { - type: "span"; - fileName: string; - textSpan: TextSpan; - } - function nodeEntry(node: Node, isInString?: true): NodeEntry; - interface Options { - readonly findInStrings?: boolean; - readonly findInComments?: boolean; - /** - * True if we are renaming the symbol. - * If so, we will find fewer references -- if it is referenced by several different names, we sill only find references for the original name. - */ - readonly isForRename?: boolean; - /** True if we are searching for implementations. We will have a different method of adding references if so. */ - readonly implementations?: boolean; - } - function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined; - function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number): ImplementationLocation[] | undefined; - function findReferencedEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number, options: Options | undefined): ReferenceEntry[] | undefined; - function getReferenceEntriesForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options?: Options, sourceFilesSet?: ReadonlyMap): Entry[] | undefined; - function toHighlightSpan(entry: Entry): { - fileName: string; - span: HighlightSpan; - }; -} -/** Encapsulates the core find-all-references algorithm. */ -declare namespace ts.FindAllReferences.Core { - /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options?: Options, sourceFilesSet?: ReadonlyMap): SymbolAndEntries[] | undefined; - function eachExportReference(sourceFiles: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken | undefined, exportSymbol: Symbol, exportingModuleSymbol: Symbol, exportName: string, isDefaultExport: boolean, cb: (ref: Identifier) => void): void; - /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ - function isSymbolReferencedInFile(definition: Identifier, checker: TypeChecker, sourceFile: SourceFile): boolean; - function eachSymbolReferenceInFile(definition: Identifier, checker: TypeChecker, sourceFile: SourceFile, cb: (token: Identifier) => T): T | undefined; - function eachSignatureCall(signature: SignatureDeclaration, sourceFiles: ReadonlyArray, checker: TypeChecker, cb: (call: CallExpression) => void): void; - /** - * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations - * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class - * then we need to widen the search to include type positions as well. - * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated - * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) - * do not intersect in any of the three spaces. - */ - function getIntersectingMeaningFromDeclarations(node: Node, symbol: Symbol): SemanticMeaning; - function getReferenceEntriesForShorthandPropertyAssignment(node: Node, checker: TypeChecker, addReference: (node: Node) => void): void; -} -declare namespace ts { - function getEditsForFileRename(program: Program, oldFileOrDirPath: string, newFileOrDirPath: string, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences): ReadonlyArray; - /** If 'path' refers to an old directory, returns path in the new directory. */ - type PathUpdater = (path: string) => string | undefined; - function getPathUpdater(oldFileOrDirPath: string, newFileOrDirPath: string, getCanonicalFileName: GetCanonicalFileName): PathUpdater; -} -declare namespace ts.GoToDefinition { - function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): DefinitionInfo[] | undefined; - function getReferenceAtPosition(sourceFile: SourceFile, position: number, program: Program): { - fileName: string; - file: SourceFile; - } | undefined; - function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[] | undefined; - function getDefinitionAndBoundSpan(program: Program, sourceFile: SourceFile, position: number): DefinitionInfoAndBoundSpan | undefined; - function findReferenceInPosition(refs: ReadonlyArray, pos: number): FileReference | undefined; -} -declare namespace ts.JsDoc { - function getJsDocCommentsFromDeclarations(declarations: ReadonlyArray): SymbolDisplayPart[]; - function getJsDocTagsFromDeclarations(declarations?: Declaration[]): JSDocTagInfo[]; - function getJSDocTagNameCompletions(): CompletionEntry[]; - const getJSDocTagNameCompletionDetails: typeof getJSDocTagCompletionDetails; - function getJSDocTagCompletions(): CompletionEntry[]; - function getJSDocTagCompletionDetails(name: string): CompletionEntryDetails; - function getJSDocParameterNameCompletions(tag: JSDocParameterTag): CompletionEntry[]; - function getJSDocParameterNameCompletionDetails(name: string): CompletionEntryDetails; - /** - * Checks if position points to a valid position to add JSDoc comments, and if so, - * returns the appropriate template. Otherwise returns an empty string. - * Valid positions are - * - outside of comments, statements, and expressions, and - * - preceding a: - * - function/constructor/method declaration - * - class declarations - * - variable statements - * - namespace declarations - * - interface declarations - * - method signatures - * - type alias declarations - * - * Hosts should ideally check that: - * - The line is all whitespace up to 'position' before performing the insertion. - * - If the keystroke sequence "/\*\*" induced the call, we also check that the next - * non-whitespace character is '*', which (approximately) indicates whether we added - * the second '*' to complete an existing (JSDoc) comment. - * @param fileName The file in which to perform the check. - * @param position The (character-indexed) position in the file where the check should - * be performed. - */ - function getDocCommentTemplateAtPosition(newLine: string, sourceFile: SourceFile, position: number): TextInsertion | undefined; -} -declare namespace ts.NavigateTo { - function getNavigateToItems(sourceFiles: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number | undefined, excludeDtsFiles: boolean): NavigateToItem[]; -} -declare namespace ts.NavigationBar { - function getNavigationBarItems(sourceFile: SourceFile, cancellationToken: CancellationToken): NavigationBarItem[]; - function getNavigationTree(sourceFile: SourceFile, cancellationToken: CancellationToken): NavigationTree; -} -declare namespace ts.OrganizeImports { - /** - * Organize imports by: - * 1) Removing unused imports - * 2) Coalescing imports from the same module - * 3) Sorting imports - */ - function organizeImports(sourceFile: SourceFile, formatContext: formatting.FormatContext, host: LanguageServiceHost, program: Program, _preferences: UserPreferences): FileTextChanges[]; - /** - * @param importGroup a list of ImportDeclarations, all with the same module name. - */ - function coalesceImports(importGroup: ReadonlyArray): ReadonlyArray; - /** - * @param exportGroup a list of ExportDeclarations, all with the same module name. - */ - function coalesceExports(exportGroup: ReadonlyArray): ReadonlyArray; - function compareModuleSpecifiers(m1: Expression, m2: Expression): Comparison; -} -declare namespace ts.OutliningElementsCollector { - function collectElements(sourceFile: SourceFile, cancellationToken: CancellationToken): OutliningSpan[]; -} -declare namespace ts { - enum PatternMatchKind { - exact = 0, - prefix = 1, - substring = 2, - camelCase = 3 - } - interface PatternMatch { - kind: PatternMatchKind; - isCaseSensitive: boolean; - } - interface PatternMatcher { - getMatchForLastSegmentOfPattern(candidate: string): PatternMatch | undefined; - getFullMatch(candidateContainers: ReadonlyArray, candidate: string): PatternMatch | undefined; - patternContainsDots: boolean; - } - function createPatternMatcher(pattern: string): PatternMatcher | undefined; - function breakIntoCharacterSpans(identifier: string): TextSpan[]; - function breakIntoWordSpans(identifier: string): TextSpan[]; } declare namespace ts { function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; } -declare namespace ts.Rename { - function getRenameInfo(program: Program, sourceFile: SourceFile, position: number): RenameInfo; -} -declare namespace ts.SignatureHelp { - function getSignatureHelpItems(program: Program, sourceFile: SourceFile, position: number, triggerReason: SignatureHelpTriggerReason | undefined, cancellationToken: CancellationToken): SignatureHelpItems | undefined; - interface ArgumentInfoForCompletions { - readonly invocation: CallLikeExpression; - readonly argumentIndex: number; - readonly argumentCount: number; - } - function getArgumentInfoForCompletions(node: Node, position: number, sourceFile: SourceFile): ArgumentInfoForCompletions | undefined; -} -declare namespace ts { - function computeSuggestionDiagnostics(sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): DiagnosticWithLocation[]; -} -declare namespace ts.SymbolDisplay { - function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind; - function getSymbolModifiers(symbol: Symbol): string; - interface SymbolDisplayPartsDocumentationAndSymbolKind { - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - symbolKind: ScriptElementKind; - tags: JSDocTagInfo[] | undefined; - } - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node | undefined, location: Node, semanticMeaning?: SemanticMeaning, alias?: Symbol): SymbolDisplayPartsDocumentationAndSymbolKind; -} declare namespace ts { interface TranspileOptions { compilerOptions?: CompilerOptions; @@ -11352,519 +5647,10 @@ declare namespace ts { } function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; - /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ - function fixupCompilerOptions(options: CompilerOptions, diagnostics: Diagnostic[]): CompilerOptions; -} -declare namespace ts.formatting { - enum FormattingRequestKind { - FormatDocument = 0, - FormatSelection = 1, - FormatOnEnter = 2, - FormatOnSemicolon = 3, - FormatOnOpeningCurlyBrace = 4, - FormatOnClosingCurlyBrace = 5 - } - class FormattingContext { - readonly sourceFile: SourceFileLike; - formattingRequestKind: FormattingRequestKind; - options: FormatCodeSettings; - currentTokenSpan: TextRangeWithKind; - nextTokenSpan: TextRangeWithKind; - contextNode: Node; - currentTokenParent: Node; - nextTokenParent: Node; - private contextNodeAllOnSameLine; - private nextNodeAllOnSameLine; - private tokensAreOnSameLine; - private contextNodeBlockIsOnOneLine; - private nextNodeBlockIsOnOneLine; - constructor(sourceFile: SourceFileLike, formattingRequestKind: FormattingRequestKind, options: FormatCodeSettings); - updateContext(currentRange: TextRangeWithKind, currentTokenParent: Node, nextRange: TextRangeWithKind, nextTokenParent: Node, commonParent: Node): void; - ContextNodeAllOnSameLine(): boolean; - NextNodeAllOnSameLine(): boolean; - TokensAreOnSameLine(): boolean; - ContextNodeBlockIsOnOneLine(): boolean; - NextNodeBlockIsOnOneLine(): boolean; - private NodeIsOnOneLine; - private BlockIsOnOneLine; - } -} -declare namespace ts.formatting { - interface FormattingScanner { - advance(): void; - isOnToken(): boolean; - readTokenInfo(n: Node): TokenInfo; - getCurrentLeadingTrivia(): TextRangeWithKind[] | undefined; - lastTrailingTriviaWasNewLine(): boolean; - skipToEndOf(node: Node): void; - } - function getFormattingScanner(text: string, languageVariant: LanguageVariant, startPos: number, endPos: number, cb: (scanner: FormattingScanner) => T): T; -} -declare namespace ts.formatting { - interface Rule { - readonly debugName: string; - readonly context: ReadonlyArray; - readonly action: RuleAction; - readonly flags: RuleFlags; - } - type ContextPredicate = (context: FormattingContext) => boolean; - const anyContext: ReadonlyArray; - enum RuleAction { - Ignore = 1, - Space = 2, - NewLine = 4, - Delete = 8 - } - enum RuleFlags { - None = 0, - CanDeleteNewLines = 1 - } - interface TokenRange { - readonly tokens: ReadonlyArray; - readonly isSpecific: boolean; - } -} -declare namespace ts.formatting { - interface RuleSpec { - readonly leftTokenRange: TokenRange; - readonly rightTokenRange: TokenRange; - readonly rule: Rule; - } - function getAllRules(): RuleSpec[]; -} -declare namespace ts.formatting { - function getFormatContext(options: FormatCodeSettings): FormatContext; - type RulesMap = (context: FormattingContext) => Rule | undefined; -} -declare namespace ts.formatting { - interface FormatContext { - readonly options: FormatCodeSettings; - readonly getRule: RulesMap; - } - interface TextRangeWithKind extends TextRange { - kind: SyntaxKind; - } - interface TextRangeWithTriviaKind extends TextRange { - kind: TriviaKind; - } - interface TokenInfo { - leadingTrivia: TextRangeWithTriviaKind[] | undefined; - token: TextRangeWithKind; - trailingTrivia: TextRangeWithTriviaKind[] | undefined; - } - function formatOnEnter(position: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[]; - function formatOnSemicolon(position: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[]; - function formatOnOpeningCurly(position: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[]; - function formatOnClosingCurly(position: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[]; - function formatDocument(sourceFile: SourceFile, formatContext: FormatContext): TextChange[]; - function formatSelection(start: number, end: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[]; - function formatNodeGivenIndentation(node: Node, sourceFileLike: SourceFileLike, languageVariant: LanguageVariant, initialIndentation: number, delta: number, formatContext: FormatContext): TextChange[]; - /** - * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. - */ - function getRangeOfEnclosingComment(sourceFile: SourceFile, position: number, precedingToken?: Node | null, // tslint:disable-line:no-null-keyword - tokenAtPosition?: Node): CommentRange | undefined; - function getIndentationString(indentation: number, options: EditorSettings): string; -} -declare namespace ts.formatting { - namespace SmartIndenter { - /** - * @param assumeNewLineBeforeCloseBrace - * `false` when called on text from a real source file. - * `true` when we need to assume `position` is on a newline. - * - * This is useful for codefixes. Consider - * ``` - * function f() { - * |} - * ``` - * with `position` at `|`. - * - * When inserting some text after an open brace, we would like to get indentation as if a newline was already there. - * By default indentation at `position` will be 0 so 'assumeNewLineBeforeCloseBrace' overrides this behavior. - */ - function getIndentation(position: number, sourceFile: SourceFile, options: EditorSettings, assumeNewLineBeforeCloseBrace?: boolean): number; - function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: EditorSettings): number; - function getBaseIndentation(options: EditorSettings): number; - function isArgumentAndStartLineOverlapsExpressionBeingCalled(parent: Node, child: Node, childStartLine: number, sourceFile: SourceFileLike): boolean; - function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFileLike): boolean; - function getContainingList(node: Node, sourceFile: SourceFile): NodeArray | undefined; - /** - * Character is the actual index of the character since the beginning of the line. - * Column - position of the character after expanding tabs to spaces. - * "0\t2$" - * value of 'character' for '$' is 3 - * value of 'column' for '$' is 6 (assuming that tab size is 4) - */ - function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFileLike, options: EditorSettings): { - column: number; - character: number; - }; - function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFileLike, options: EditorSettings): number; - function nodeWillIndentChild(settings: FormatCodeSettings, parent: TextRangeWithKind, child: TextRangeWithKind | undefined, sourceFile: SourceFileLike | undefined, indentByDefault: boolean): boolean; - /** - * True when the parent node should indent the given child by an explicit rule. - * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. - */ - function shouldIndentChildNode(settings: FormatCodeSettings, parent: TextRangeWithKind, child?: Node, sourceFile?: SourceFileLike, isNextChild?: boolean): boolean; - } -} -declare namespace ts.textChanges { - interface ConfigurableStart { - /** True to use getStart() (NB, not getFullStart()) without adjustment. */ - useNonAdjustedStartPosition?: boolean; - } - interface ConfigurableEnd { - /** True to use getEnd() without adjustment. */ - useNonAdjustedEndPosition?: boolean; - } - enum Position { - FullStart = 0, - Start = 1 - } - /** - * Usually node.pos points to a position immediately after the previous token. - * If this position is used as a beginning of the span to remove - it might lead to removing the trailing trivia of the previous node, i.e: - * const x; // this is x - * ^ - pos for the next variable declaration will point here - * const y; // this is y - * ^ - end for previous variable declaration - * Usually leading trivia of the variable declaration 'y' should not include trailing trivia (whitespace, comment 'this is x' and newline) from the preceding - * variable declaration and trailing trivia for 'y' should include (whitespace, comment 'this is y', newline). - * By default when removing nodes we adjust start and end positions to respect specification of the trivia above. - * If pos\end should be interpreted literally 'useNonAdjustedStartPosition' or 'useNonAdjustedEndPosition' should be set to true - */ - interface ConfigurableStartEnd extends ConfigurableStart, ConfigurableEnd { - } - const useNonAdjustedPositions: ConfigurableStartEnd; - interface InsertNodeOptions { - /** - * Text to be inserted before the new node - */ - prefix?: string; - /** - * Text to be inserted after the new node - */ - suffix?: string; - /** - * Text of inserted node will be formatted with this indentation, otherwise indentation will be inferred from the old node - */ - indentation?: number; - /** - * Text of inserted node will be formatted with this delta, otherwise delta will be inferred from the new node kind - */ - delta?: number; - /** - * Do not trim leading white spaces in the edit range - */ - preserveLeadingWhitespace?: boolean; - } - interface ReplaceWithMultipleNodesOptions extends InsertNodeOptions { - readonly joiner?: string; - } - interface ChangeNodeOptions extends ConfigurableStartEnd, InsertNodeOptions { - } - interface TextChangesContext { - host: LanguageServiceHost; - formatContext: formatting.FormatContext; - } - type TypeAnnotatable = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration | PropertySignature; - class ChangeTracker { - private readonly newLineCharacter; - private readonly formatContext; - private readonly changes; - private readonly newFiles; - private readonly classesWithNodesInsertedAtStart; - private readonly deletedNodes; - static fromContext(context: TextChangesContext): ChangeTracker; - static with(context: TextChangesContext, cb: (tracker: ChangeTracker) => void): FileTextChanges[]; - /** Public for tests only. Other callers should use `ChangeTracker.with`. */ - constructor(newLineCharacter: string, formatContext: formatting.FormatContext); - deleteRange(sourceFile: SourceFile, range: TextRange): this; - delete(sourceFile: SourceFile, node: Node): void; - deleteModifier(sourceFile: SourceFile, modifier: Modifier): void; - deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options?: ConfigurableStartEnd): this; - deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options?: ConfigurableStartEnd): void; - replaceRange(sourceFile: SourceFile, range: TextRange, newNode: Node, options?: InsertNodeOptions): this; - replaceNode(sourceFile: SourceFile, oldNode: Node, newNode: Node, options?: ChangeNodeOptions): this; - replaceNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, newNode: Node, options?: ChangeNodeOptions): void; - private replaceRangeWithNodes; - replaceNodeWithNodes(sourceFile: SourceFile, oldNode: Node, newNodes: ReadonlyArray, options?: ChangeNodeOptions): this; - replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: ReadonlyArray, options?: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd): this; - private nextCommaToken; - replacePropertyAssignment(sourceFile: SourceFile, oldNode: PropertyAssignment, newNode: PropertyAssignment): this; - insertNodeAt(sourceFile: SourceFile, pos: number, newNode: Node, options?: InsertNodeOptions): void; - private insertNodesAt; - insertNodeAtTopOfFile(sourceFile: SourceFile, newNode: Statement, blankLineBetween: boolean): void; - insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween?: boolean): void; - insertModifierBefore(sourceFile: SourceFile, modifier: SyntaxKind, before: Node): void; - insertCommentBeforeLine(sourceFile: SourceFile, lineNumber: number, position: number, commentText: string): void; - replaceRangeWithText(sourceFile: SourceFile, range: TextRange, text: string): void; - private insertText; - /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ - tryInsertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): void; - insertTypeParameters(sourceFile: SourceFile, node: SignatureDeclaration, typeParameters: ReadonlyArray): void; - private getOptionsForInsertNodeBefore; - insertNodeAtConstructorStart(sourceFile: SourceFile, ctr: ConstructorDeclaration, newStatement: Statement): void; - insertNodeAtConstructorEnd(sourceFile: SourceFile, ctr: ConstructorDeclaration, newStatement: Statement): void; - private replaceConstructorBody; - insertNodeAtEndOfScope(sourceFile: SourceFile, scope: Node, newNode: Node): void; - insertNodeAtClassStart(sourceFile: SourceFile, cls: ClassLikeDeclaration, newElement: ClassElement): void; - private getInsertNodeAtClassStartPrefixSuffix; - insertNodeAfterComma(sourceFile: SourceFile, after: Node, newNode: Node): void; - insertNodeAfter(sourceFile: SourceFile, after: Node, newNode: Node): void; - insertNodeAtEndOfList(sourceFile: SourceFile, list: NodeArray, newNode: Node): void; - insertNodesAfter(sourceFile: SourceFile, after: Node, newNodes: ReadonlyArray): void; - private insertNodeAfterWorker; - private getInsertNodeAfterOptions; - private getInsertNodeAfterOptionsWorker; - insertName(sourceFile: SourceFile, node: FunctionExpression | ClassExpression | ArrowFunction, name: string): void; - insertExportModifier(sourceFile: SourceFile, node: DeclarationStatement | VariableStatement): void; - /** - * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, - * i.e. arguments in arguments lists, parameters in parameter lists etc. - * Note that separators are part of the node in statements and class elements. - */ - insertNodeInListAfter(sourceFile: SourceFile, after: Node, newNode: Node, containingList?: NodeArray | undefined): this; - private finishClassesWithNodesInsertedAtStart; - private finishDeleteDeclarations; - /** - * Note: after calling this, the TextChanges object must be discarded! - * @param validate only for tests - * The reason we must validate as part of this method is that `getNonFormattedText` changes the node's positions, - * so we can only call this once and can't get the non-formatted text separately. - */ - getChanges(validate?: ValidateNonFormattedText): FileTextChanges[]; - createNewFile(oldFile: SourceFile, fileName: string, statements: ReadonlyArray): void; - } - type ValidateNonFormattedText = (node: Node, text: string) => void; - function applyChanges(text: string, changes: ReadonlyArray): string; - function isValidLocationToAddComment(sourceFile: SourceFile, position: number): boolean; - /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ - function deleteNode(changes: ChangeTracker, sourceFile: SourceFile, node: Node, options?: ConfigurableStartEnd): void; -} -declare namespace ts { - interface CodeFixRegistration { - errorCodes: ReadonlyArray; - getCodeActions(context: CodeFixContext): CodeFixAction[] | undefined; - fixIds?: ReadonlyArray; - getAllCodeActions?(context: CodeFixAllContext): CombinedCodeActions; - } - interface CodeFixContextBase extends textChanges.TextChangesContext { - sourceFile: SourceFile; - program: Program; - cancellationToken: CancellationToken; - preferences: UserPreferences; - } - interface CodeFixAllContext extends CodeFixContextBase { - fixId: {}; - } - interface CodeFixContext extends CodeFixContextBase { - errorCode: number; - span: TextSpan; - } - namespace codefix { - type DiagnosticAndArguments = DiagnosticMessage | [DiagnosticMessage, string] | [DiagnosticMessage, string, string]; - function createCodeFixActionNoFixId(fixName: string, changes: FileTextChanges[], description: DiagnosticAndArguments): CodeFixAction; - function createCodeFixAction(fixName: string, changes: FileTextChanges[], description: DiagnosticAndArguments, fixId: {}, fixAllDescription: DiagnosticAndArguments, command?: CodeActionCommand): CodeFixAction; - function registerCodeFix(reg: CodeFixRegistration): void; - function getSupportedErrorCodes(): string[]; - function getFixes(context: CodeFixContext): CodeFixAction[]; - function getAllFixes(context: CodeFixAllContext): CombinedCodeActions; - function createCombinedCodeActions(changes: FileTextChanges[], commands?: CodeActionCommand[]): CombinedCodeActions; - function createFileTextChanges(fileName: string, textChanges: TextChange[]): FileTextChanges; - function codeFixAll(context: CodeFixAllContext, errorCodes: number[], use: (changes: textChanges.ChangeTracker, error: DiagnosticWithLocation, commands: Push) => void): CombinedCodeActions; - function eachDiagnostic({ program, sourceFile, cancellationToken }: CodeFixAllContext, errorCodes: ReadonlyArray, cb: (diag: DiagnosticWithLocation) => void): void; - } -} -declare namespace ts { - interface Refactor { - /** Compute the associated code actions */ - getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined; - /** Compute (quickly) which actions are available here */ - getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined; - } - interface RefactorContext extends textChanges.TextChangesContext { - file: SourceFile; - startPosition: number; - endPosition?: number; - program: Program; - cancellationToken?: CancellationToken; - preferences: UserPreferences; - } - namespace refactor { - /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ - function registerRefactor(name: string, refactor: Refactor): void; - function getApplicableRefactors(context: RefactorContext): ApplicableRefactorInfo[]; - function getEditsForRefactor(context: RefactorContext, refactorName: string, actionName: string): RefactorEditInfo | undefined; - } - function getRefactorContextSpan({ startPosition, endPosition }: RefactorContext): TextSpan; -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { - type DeclarationWithType = FunctionLikeDeclaration | VariableDeclaration | PropertySignature | PropertyDeclaration; - function parameterShouldGetTypeFromJSDoc(node: Node): node is DeclarationWithType; -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { - const importFixId = "fixMissingImport"; - function getImportCompletionAction(exportedSymbol: Symbol, moduleSymbol: Symbol, sourceFile: SourceFile, symbolName: string, host: LanguageServiceHost, program: Program, checker: TypeChecker, allSourceFiles: ReadonlyArray, formatContext: formatting.FormatContext, symbolToken: Node | undefined, preferences: UserPreferences): { - readonly moduleSpecifier: string; - readonly codeAction: CodeAction; - }; - function forEachExternalModuleToImportFrom(checker: TypeChecker, from: SourceFile, allSourceFiles: ReadonlyArray, cb: (module: Symbol) => void): void; - function moduleSymbolToValidIdentifier(moduleSymbol: Symbol, target: ScriptTarget): string; - function moduleSpecifierToValidIdentifier(moduleSpecifier: string, target: ScriptTarget): string; -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { - /** - * Finds members of the resolved type that are missing in the class pointed to by class decl - * and generates source code for the missing members. - * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. - * @returns Empty string iff there are no member insertions. - */ - function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray, checker: TypeChecker, preferences: UserPreferences, out: (node: ClassElement) => void): void; - function createMethodFromCallExpression(context: CodeFixContextBase, { typeArguments, arguments: args, parent: parent }: CallExpression, methodName: string, inJs: boolean, makeStatic: boolean, preferences: UserPreferences): MethodDeclaration; -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.codefix { -} -declare namespace ts.refactor { -} -declare namespace ts.refactor { -} -declare namespace ts.refactor.extractSymbol { - /** - * Compute the associated code actions - * Exported for tests. - */ - function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined; - function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined; - namespace Messages { - const cannotExtractRange: DiagnosticMessage; - const cannotExtractImport: DiagnosticMessage; - const cannotExtractSuper: DiagnosticMessage; - const cannotExtractEmpty: DiagnosticMessage; - const expressionExpected: DiagnosticMessage; - const uselessConstantType: DiagnosticMessage; - const statementOrExpressionExpected: DiagnosticMessage; - const cannotExtractRangeContainingConditionalBreakOrContinueStatements: DiagnosticMessage; - const cannotExtractRangeContainingConditionalReturnStatement: DiagnosticMessage; - const cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange: DiagnosticMessage; - const cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators: DiagnosticMessage; - const typeWillNotBeVisibleInTheNewScope: DiagnosticMessage; - const functionWillNotBeVisibleInTheNewScope: DiagnosticMessage; - const cannotExtractIdentifier: DiagnosticMessage; - const cannotExtractExportedEntity: DiagnosticMessage; - const cannotWriteInExpression: DiagnosticMessage; - const cannotExtractReadonlyPropertyInitializerOutsideConstructor: DiagnosticMessage; - const cannotExtractAmbientBlock: DiagnosticMessage; - const cannotAccessVariablesFromNestedScopes: DiagnosticMessage; - const cannotExtractToOtherFunctionLike: DiagnosticMessage; - const cannotExtractToJSClass: DiagnosticMessage; - const cannotExtractToExpressionArrowFunction: DiagnosticMessage; - } - enum RangeFacts { - None = 0, - HasReturn = 1, - IsGenerator = 2, - IsAsyncFunction = 4, - UsesThis = 8, - /** - * The range is in a function which needs the 'static' modifier in a class - */ - InStaticRegion = 16 - } - /** - * Represents an expression or a list of statements that should be extracted with some extra information - */ - interface TargetRange { - readonly range: Expression | Statement[]; - readonly facts: RangeFacts; - /** - * A list of symbols that are declared in the selected range which are visible in the containing lexical scope - * Used to ensure we don't turn something used outside the range free (or worse, resolve to a different entity). - */ - readonly declarations: Symbol[]; - } - /** - * Result of 'getRangeToExtract' operation: contains either a range or a list of errors - */ - type RangeToExtract = { - readonly targetRange?: never; - readonly errors: ReadonlyArray; - } | { - readonly targetRange: TargetRange; - readonly errors?: never; - }; - /** - * 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) - */ - function getRangeToExtract(sourceFile: SourceFile, span: TextSpan): RangeToExtract; -} -declare namespace ts.refactor.generateGetAccessorAndSetAccessor { -} -declare namespace ts.refactor { -} -declare namespace ts.refactor.addOrRemoveBracesToArrowFunction { } declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; - interface DisplayPartsSymbolWriter extends EmitTextWriter { - displayParts(): SymbolDisplayPart[]; - } - function toEditorSettings(options: FormatCodeOptions | FormatCodeSettings): FormatCodeSettings; function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string; function getDefaultCompilerOptions(): CompilerOptions; @@ -11872,24 +5658,7 @@ declare namespace ts { function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile; - /** A cancellation that throttles calls to the host */ - class ThrottledCancellationToken implements CancellationToken { - private hostCancellationToken; - private readonly throttleWaitMilliseconds; - private lastCancellationCheckTime; - constructor(hostCancellationToken: HostCancellationToken, throttleWaitMilliseconds?: number); - isCancellationRequested(): boolean; - throwIfCancellationRequested(): void; - } function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnly?: boolean): LanguageService; - /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */ - function getNameTable(sourceFile: SourceFile): UnderscoreEscapedMap; - /** - * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } - */ - function getContainingObjectLiteralElement(node: Node): ObjectLiteralElement | undefined; - function getPropertySymbolsFromContextualType(typeChecker: TypeChecker, node: ObjectLiteralElement): Symbol[]; - function getPropertySymbolsFromType(type: Type, propName: PropertyName): Symbol[] | undefined; /** * Get the path of the default library files (lib.d.ts) as distributed with the typescript * node package. @@ -11897,12 +5666,6 @@ declare namespace ts { */ function getDefaultLibFilePath(options: CompilerOptions): string; } -declare namespace ts.BreakpointResolver { - /** - * Get the breakpoint span in given sourceFile - */ - function spanInSourceFileAtLocation(sourceFile: SourceFile, position: number): TextSpan | undefined; -} declare namespace ts { /** * Transform one or more nodes using the supplied transformers. @@ -11912,283 +5675,11 @@ declare namespace ts { */ function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions): TransformationResult; } -declare let debugObjectHost: { - CollectGarbage(): void; -}; -declare namespace ts { - interface ScriptSnapshotShim { - /** Gets a portion of the script snapshot specified by [start, end). */ - getText(start: number, end: number): string; - /** Gets the length of this script snapshot. */ - getLength(): number; - /** - * Returns a JSON-encoded value of the type: - * { span: { start: number; length: number }; newLength: number } - * - * Or undefined value if there was no change. - */ - getChangeRange(oldSnapshot: ScriptSnapshotShim): string | undefined; - /** Releases all resources held by this script snapshot */ - dispose?(): void; - } - interface Logger { - log(s: string): void; - trace(s: string): void; - error(s: string): void; - } - /** Public interface of the host of a language service shim instance. */ - interface LanguageServiceShimHost extends Logger { - getCompilationSettings(): string; - /** Returns a JSON-encoded value of the type: string[] */ - getScriptFileNames(): string; - getScriptKind?(fileName: string): ScriptKind; - getScriptVersion(fileName: string): string; - getScriptSnapshot(fileName: string): ScriptSnapshotShim; - getLocalizedDiagnosticMessages(): string; - getCancellationToken(): HostCancellationToken; - getCurrentDirectory(): string; - getDirectories(path: string): string; - getDefaultLibFileName(options: string): string; - getNewLine?(): string; - getProjectVersion?(): string; - useCaseSensitiveFileNames?(): boolean; - getTypeRootsVersion?(): number; - readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; - readFile(path: string, encoding?: string): string | undefined; - fileExists(path: string): boolean; - getModuleResolutionsForFile?(fileName: string): string; - getTypeReferenceDirectiveResolutionsForFile?(fileName: string): string; - directoryExists(directoryName: string): boolean; - } - /** Public interface of the core-services host instance used in managed side */ - interface CoreServicesShimHost extends Logger { - directoryExists(directoryName: string): boolean; - fileExists(fileName: string): boolean; - getCurrentDirectory(): string; - getDirectories(path: string): string; - /** - * Returns a JSON-encoded value of the type: string[] - * - * @param exclude A JSON encoded string[] containing the paths to exclude - * when enumerating the directory. - */ - readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; - /** - * Read arbitrary text files on disk, i.e. when resolution procedure needs the content of 'package.json' to determine location of bundled typings for node modules - */ - readFile(fileName: string): string | undefined; - realpath?(path: string): string; - trace(s: string): void; - useCaseSensitiveFileNames?(): boolean; - } - interface ShimsFileReference { - path: string; - position: number; - length: number; - } - /** Public interface of a language service instance shim. */ - interface ShimFactory { - registerShim(shim: Shim): void; - unregisterShim(shim: Shim): void; - } - interface Shim { - dispose(_dummy: {}): void; - } - interface LanguageServiceShim extends Shim { - languageService: LanguageService; - dispose(_dummy: {}): void; - refresh(throwOnError: boolean): void; - cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): string; - getSemanticDiagnostics(fileName: string): string; - getSuggestionDiagnostics(fileName: string): string; - getCompilerOptionsDiagnostics(): string; - getSyntacticClassifications(fileName: string, start: number, length: number): string; - getSemanticClassifications(fileName: string, start: number, length: number): string; - getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string; - getEncodedSemanticClassifications(fileName: string, start: number, length: number): string; - getCompletionsAtPosition(fileName: string, position: number, preferences: UserPreferences | undefined): string; - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string | undefined, source: string | undefined, preferences: UserPreferences | undefined): string; - getQuickInfoAtPosition(fileName: string, position: number): string; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string; - getBreakpointStatementAtPosition(fileName: string, position: number): string; - getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): string; - /** - * Returns a JSON-encoded value of the type: - * { canRename: boolean, localizedErrorMessage: string, displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, triggerSpan: { start; length } } - */ - getRenameInfo(fileName: string, position: number): string; - /** - * Returns a JSON-encoded value of the type: - * { fileName: string, textSpan: { start: number, length: number } }[] - */ - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string; - /** - * Returns a JSON-encoded value of the type: - * { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string } - * - * Or undefined value if no definition can be found. - */ - getDefinitionAtPosition(fileName: string, position: number): string; - getDefinitionAndBoundSpan(fileName: string, position: number): string; - /** - * Returns a JSON-encoded value of the type: - * { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string } - * - * Or undefined value if no definition can be found. - */ - getTypeDefinitionAtPosition(fileName: string, position: number): string; - /** - * Returns a JSON-encoded value of the type: - * { fileName: string; textSpan: { start: number; length: number}; }[] - */ - getImplementationAtPosition(fileName: string, position: number): string; - /** - * Returns a JSON-encoded value of the type: - * { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean, isDefinition?: boolean }[] - */ - getReferencesAtPosition(fileName: string, position: number): string; - /** - * Returns a JSON-encoded value of the type: - * { definition: ; references: [] }[] - */ - findReferences(fileName: string, position: number): string; - /** - * @deprecated - * Returns a JSON-encoded value of the type: - * { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[] - */ - getOccurrencesAtPosition(fileName: string, position: number): string; - /** - * Returns a JSON-encoded value of the type: - * { fileName: string; highlights: { start: number; length: number, isDefinition: boolean }[] }[] - * - * @param fileToSearch A JSON encoded string[] containing the file names that should be - * considered when searching. - */ - getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string; - /** - * Returns a JSON-encoded value of the type: - * { name: string; kind: string; kindModifiers: string; containerName: string; containerKind: string; matchKind: string; fileName: string; textSpan: { start: number; length: number}; } [] = []; - */ - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string; - /** - * Returns a JSON-encoded value of the type: - * { text: string; kind: string; kindModifiers: string; bolded: boolean; grayed: boolean; indent: number; spans: { start: number; length: number; }[]; childItems: [] } [] = []; - */ - getNavigationBarItems(fileName: string): string; - /** Returns a JSON-encoded value of the type ts.NavigationTree. */ - getNavigationTree(fileName: string): string; - /** - * Returns a JSON-encoded value of the type: - * { textSpan: { start: number, length: number }; hintSpan: { start: number, length: number }; bannerText: string; autoCollapse: boolean } [] = []; - */ - getOutliningSpans(fileName: string): string; - getTodoComments(fileName: string, todoCommentDescriptors: string): string; - getBraceMatchingAtPosition(fileName: string, position: number): string; - getIndentationAtPosition(fileName: string, position: number, options: string): string; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: string): string; - getFormattingEditsForDocument(fileName: string, options: string): string; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string): string; - /** - * Returns JSON-encoded value of the type TextInsertion. - */ - getDocCommentTemplateAtPosition(fileName: string, position: number): string; - /** - * Returns JSON-encoded boolean to indicate whether we should support brace location - * at the current position. - * E.g. we don't want brace completion inside string-literals, comments, etc. - */ - isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string; - /** - * Returns a JSON-encoded TextSpan | undefined indicating the range of the enclosing comment, if it exists. - */ - getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): string; - getEmitOutput(fileName: string): string; - getEmitOutputObject(fileName: string): EmitOutput; - } - interface ClassifierShim extends Shim { - getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string; - getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string; - } - interface CoreServicesShim extends Shim { - getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string; - getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string; - getTSConfigFileInfo(fileName: string, sourceText: IScriptSnapshot): string; - getDefaultCompilationSettings(): string; - discoverTypings(discoverTypingsJson: string): string; - } - class LanguageServiceShimHostAdapter implements LanguageServiceHost { - private shimHost; - private files; - private loggingEnabled; - private tracingEnabled; - resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModuleFull[]; - resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[]; - directoryExists: (directoryName: string) => boolean; - constructor(shimHost: LanguageServiceShimHost); - log(s: string): void; - trace(s: string): void; - error(s: string): void; - getProjectVersion(): string; - getTypeRootsVersion(): number; - useCaseSensitiveFileNames(): boolean; - getCompilationSettings(): CompilerOptions; - getScriptFileNames(): string[]; - getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; - getScriptKind(fileName: string): ScriptKind; - getScriptVersion(fileName: string): string; - getLocalizedDiagnosticMessages(): any; - getCancellationToken(): HostCancellationToken; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - getDefaultLibFileName(options: CompilerOptions): string; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: string[], include?: string[], depth?: number): string[]; - readFile(path: string, encoding?: string): string | undefined; - fileExists(path: string): boolean; - } - class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost, JsTyping.TypingResolutionHost { - private shimHost; - directoryExists: (directoryName: string) => boolean; - realpath: (path: string) => string; - useCaseSensitiveFileNames: boolean; - constructor(shimHost: CoreServicesShimHost); - readDirectory(rootDir: string, extensions: ReadonlyArray, exclude: ReadonlyArray, include: ReadonlyArray, depth?: number): string[]; - fileExists(fileName: string): boolean; - readFile(fileName: string): string | undefined; - getDirectories(path: string): string[]; - } - interface RealizedDiagnostic { - message: string; - start: number; - length: number; - category: string; - code: number; - reportsUnnecessary?: {}; - } - function realizeDiagnostics(diagnostics: ReadonlyArray, newLine: string): RealizedDiagnostic[]; - class TypeScriptServicesFactory implements ShimFactory { - private _shims; - private documentRegistry; - getServicesVersion(): string; - createLanguageServiceShim(host: LanguageServiceShimHost): LanguageServiceShim; - createClassifierShim(logger: Logger): ClassifierShim; - createCoreServicesShim(host: CoreServicesShimHost): CoreServicesShim; - close(): void; - registerShim(shim: Shim): void; - unregisterShim(shim: Shim): void; - } -} -declare namespace TypeScript.Services { - const TypeScriptServicesFactory: typeof ts.TypeScriptServicesFactory; -} -declare const toolsVersion = "3.0"; -//# sourceMappingURL=services.d.ts.map -declare namespace ts.server { - interface CompressedData { - length: number; - compressionKind: string; - data: any; +declare namespace ts.server { + interface CompressedData { + length: number; + compressionKind: string; + data: any; } type RequireResult = { module: {}; @@ -12237,6 +5728,7 @@ declare namespace ts.server { Perf = "Perf" } namespace Msg { + /** @deprecated Only here for backwards-compatibility. Prefer just `Msg`. */ type Types = Msg; } function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, cachePath?: string): DiscoverTypings; @@ -12261,10 +5753,16 @@ declare namespace ts.server { function createNormalizedPathMap(): NormalizedPathMap; interface ProjectOptions { configHasExtendsProperty: boolean; + /** + * true if config file explicitly listed files + */ configHasFilesProperty: boolean; configHasIncludeProperty: boolean; configHasExcludeProperty: boolean; projectReferences: ReadonlyArray | undefined; + /** + * these fields can be present in the project file + */ files?: string[]; wildcardDirectories?: Map; compilerOptions?: CompilerOptions; @@ -12275,87 +5773,49 @@ declare namespace ts.server { function makeInferredProjectName(counter: number): string; function createSortedArray(): SortedArray; } -declare namespace ts.server { - class ThrottledOperations { - private readonly host; - private readonly pendingTimeouts; - private readonly logger?; - constructor(host: ServerHost, logger: Logger); - schedule(operationId: string, delay: number, cb: () => void): void; - private static run; - } - class GcTimer { - private readonly host; - private readonly delay; - private readonly logger; - private timerId; - constructor(host: ServerHost, delay: number, logger: Logger); - scheduleCollect(): void; - private static run; - } - function getBaseConfigFileName(configFilePath: NormalizedPath): "tsconfig.json" | "jsconfig.json" | undefined; - function removeSorted(array: SortedArray, remove: T, compare: Comparer): void; - function toSortedArray(arr: string[]): SortedArray; - function toSortedArray(arr: T[], comparer: Comparer): SortedArray; - function toDeduplicatedSortedArray(arr: string[]): SortedArray; - function indent(str: string): string; - function stringifyIndented(json: {}): string; -} +/** + * Declaration module describing the TypeScript Server protocol + */ declare namespace ts.server.protocol { enum CommandTypes { JsxClosingTag = "jsxClosingTag", Brace = "brace", - BraceFull = "brace-full", BraceCompletion = "braceCompletion", GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", Change = "change", Close = "close", + /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */ Completions = "completions", CompletionInfo = "completionInfo", - CompletionsFull = "completions-full", CompletionDetails = "completionEntryDetails", - CompletionDetailsFull = "completionEntryDetails-full", CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", CompileOnSaveEmitFile = "compileOnSaveEmitFile", Configure = "configure", Definition = "definition", - DefinitionFull = "definition-full", DefinitionAndBoundSpan = "definitionAndBoundSpan", - DefinitionAndBoundSpanFull = "definitionAndBoundSpan-full", Implementation = "implementation", - ImplementationFull = "implementation-full", Exit = "exit", Format = "format", Formatonkey = "formatonkey", - FormatFull = "format-full", - FormatonkeyFull = "formatonkey-full", - FormatRangeFull = "formatRange-full", Geterr = "geterr", GeterrForProject = "geterrForProject", SemanticDiagnosticsSync = "semanticDiagnosticsSync", SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", NavBar = "navbar", - NavBarFull = "navbar-full", Navto = "navto", - NavtoFull = "navto-full", NavTree = "navtree", NavTreeFull = "navtree-full", + /** @deprecated */ Occurrences = "occurrences", DocumentHighlights = "documentHighlights", - DocumentHighlightsFull = "documentHighlights-full", Open = "open", Quickinfo = "quickinfo", - QuickinfoFull = "quickinfo-full", References = "references", - ReferencesFull = "references-full", Reload = "reload", Rename = "rename", - RenameInfoFull = "rename-full", - RenameLocationsFull = "renameLocations-full", Saveto = "saveto", SignatureHelp = "signatureHelp", - SignatureHelpFull = "signatureHelp-full", Status = "status", TypeDefinition = "typeDefinition", ProjectInfo = "projectInfo", @@ -12364,59 +5824,101 @@ declare namespace ts.server.protocol { OpenExternalProject = "openExternalProject", OpenExternalProjects = "openExternalProjects", CloseExternalProject = "closeExternalProject", - SynchronizeProjectList = "synchronizeProjectList", - ApplyChangedToOpenFiles = "applyChangedToOpenFiles", - EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full", - Cleanup = "cleanup", GetOutliningSpans = "getOutliningSpans", - GetOutliningSpansFull = "outliningSpans", TodoComments = "todoComments", Indentation = "indentation", DocCommentTemplate = "docCommentTemplate", - CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full", - NameOrDottedNameSpan = "nameOrDottedNameSpan", - BreakpointStatement = "breakpointStatement", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", - GetCodeFixesFull = "getCodeFixes-full", GetCombinedCodeFix = "getCombinedCodeFix", - GetCombinedCodeFixFull = "getCombinedCodeFix-full", ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", - GetEditsForRefactorFull = "getEditsForRefactor-full", OrganizeImports = "organizeImports", - OrganizeImportsFull = "organizeImports-full", - GetEditsForFileRename = "getEditsForFileRename", - GetEditsForFileRenameFull = "getEditsForFileRename-full" + GetEditsForFileRename = "getEditsForFileRename" } + /** + * A TypeScript Server message + */ interface Message { + /** + * Sequence number of the message + */ seq: number; + /** + * One of "request", "response", or "event" + */ type: "request" | "response" | "event"; } + /** + * Client-initiated request message + */ interface Request extends Message { type: "request"; + /** + * The command to execute + */ command: string; + /** + * Object containing arguments for the command + */ arguments?: any; } + /** + * Request to reload the project structure for all the opened files + */ interface ReloadProjectsRequest extends Message { command: CommandTypes.ReloadProjects; } + /** + * Server-initiated event message + */ interface Event extends Message { type: "event"; + /** + * Name of event + */ event: string; + /** + * Event-specific information + */ body?: any; } + /** + * Response by server to client request message. + */ interface Response extends Message { type: "response"; + /** + * Sequence number of the request message. + */ request_seq: number; + /** + * Outcome of the request. + */ success: boolean; + /** + * The command requested. + */ command: string; + /** + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. + */ message?: string; + /** + * Contains message body if success === true. + */ body?: any; } + /** + * Arguments for FileRequest messages. + */ interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ file: string; projectFileName?: string; } @@ -12424,85 +5926,183 @@ declare namespace ts.server.protocol { command: CommandTypes.Status; } interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ version: string; } + /** + * Response to StatusRequest + */ interface StatusResponse extends Response { body: StatusResponseBody; } + /** + * Requests a JS Doc comment template for a given position + */ interface DocCommentTemplateRequest extends FileLocationRequest { command: CommandTypes.DocCommentTemplate; } + /** + * Response to DocCommentTemplateRequest + */ interface DocCommandTemplateResponse extends Response { body?: TextInsertion; } + /** + * A request to get TODO comments from the file + */ interface TodoCommentRequest extends FileRequest { command: CommandTypes.TodoComments; arguments: TodoCommentRequestArgs; } + /** + * Arguments for TodoCommentRequest request. + */ interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ descriptors: TodoCommentDescriptor[]; } + /** + * Response for TodoCommentRequest request. + */ interface TodoCommentsResponse extends Response { body?: TodoComment[]; } + /** + * A request to determine if the caret is inside a comment. + */ interface SpanOfEnclosingCommentRequest extends FileLocationRequest { command: CommandTypes.GetSpanOfEnclosingComment; arguments: SpanOfEnclosingCommentRequestArgs; } interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { + /** + * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. + */ onlyMultiLine: boolean; } + /** + * Request to obtain outlining spans in file. + */ interface OutliningSpansRequest extends FileRequest { command: CommandTypes.GetOutliningSpans; } interface OutliningSpan { + /** The span of the document to actually collapse. */ textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ autoCollapse: boolean; + /** + * Classification of the contents of the span + */ kind: OutliningSpanKind; } + /** + * Response to OutliningSpansRequest request. + */ interface OutliningSpansResponse extends Response { body?: OutliningSpan[]; } - interface OutliningSpansRequestFull extends FileRequest { - command: CommandTypes.GetOutliningSpansFull; - } - interface OutliningSpansResponseFull extends Response { - body?: ts.OutliningSpan[]; - } + /** + * A request to get indentation for a location in file + */ interface IndentationRequest extends FileLocationRequest { command: CommandTypes.Indentation; arguments: IndentationRequestArgs; } + /** + * Response for IndentationRequest request. + */ interface IndentationResponse extends Response { body?: IndentationResult; } + /** + * Indentation result representing where indentation should be placed + */ interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ indentation: number; } + /** + * Arguments for IndentationRequest request. + */ interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ options?: EditorSettings; } + /** + * Arguments for ProjectInfoRequest request. + */ interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ needFileNameList: boolean; } + /** + * A request to get the project information of the current file. + */ interface ProjectInfoRequest extends Request { command: CommandTypes.ProjectInfo; arguments: ProjectInfoRequestArgs; } + /** + * A request to retrieve compiler options diagnostics for a project + */ interface CompilerOptionsDiagnosticsRequest extends Request { arguments: CompilerOptionsDiagnosticsRequestArgs; } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ projectFileName: string; } + /** + * Response message body for "projectInfo" request + */ interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ languageServiceDisabled?: boolean; } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ interface DiagnosticWithLinePosition { message: string; start: number; @@ -12511,43 +6111,99 @@ declare namespace ts.server.protocol { endLocation: Location; category: string; code: number; + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ reportsUnnecessary?: {}; relatedInformation?: DiagnosticRelatedInformation[]; } + /** + * Response message for "projectInfo" request + */ interface ProjectInfoResponse extends Response { body?: ProjectInfo; } + /** + * Request whose sole parameter is a file name. + */ interface FileRequest extends Request { arguments: FileRequestArgs; } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ line: number; + /** + * The character offset (on the line) for the request (1-based). + */ offset: number; - position?: number; } type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + /** + * Request refactorings at a given position or selection area. + */ interface GetApplicableRefactorsRequest extends Request { command: CommandTypes.GetApplicableRefactors; arguments: GetApplicableRefactorsRequestArgs; } type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + /** + * Response is a list of available refactorings. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ interface GetApplicableRefactorsResponse extends Response { body?: ApplicableRefactorInfo[]; } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ inlineable?: boolean; actions: RefactorActionInfo[]; } + /** + * 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. + */ interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ name: string; - description: string; - } - interface GetEditsForRefactorRequest extends Request { - command: CommandTypes.GetEditsForRefactor; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + } + interface GetEditsForRefactorRequest extends Request { + command: CommandTypes.GetEditsForRefactor; arguments: GetEditsForRefactorRequestArgs; } + /** + * Request the edits that a particular refactoring action produces. + * Callers must specify the name of the refactor and the name of the action. + */ type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { refactor: string; action: string; @@ -12557,9 +6213,19 @@ declare namespace ts.server.protocol { } interface RefactorEditInfo { edits: FileCodeEdits[]; + /** + * An optional location where the editor should start a rename operation once + * the refactoring edits have been applied + */ renameLocation?: Location; renameFilename?: string; } + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ interface OrganizeImportsRequest extends Request { command: CommandTypes.OrganizeImports; arguments: OrganizeImportsRequestArgs; @@ -12575,6 +6241,7 @@ declare namespace ts.server.protocol { command: CommandTypes.GetEditsForFileRename; arguments: GetEditsForFileRenameRequestArgs; } + /** Note: Paths may also be directories. */ interface GetEditsForFileRenameRequestArgs { readonly oldFilePath: string; readonly newFilePath: string; @@ -12582,6 +6249,9 @@ declare namespace ts.server.protocol { interface GetEditsForFileRenameResponse extends Response { body: ReadonlyArray; } + /** + * Request for the available codefixes at a specific position. + */ interface CodeFixRequest extends Request { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; @@ -12600,15 +6270,31 @@ declare namespace ts.server.protocol { interface ApplyCodeActionCommandResponse extends Response { } interface FileRangeRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ startOffset: number; - startPosition?: number; + /** + * The line number for the request (1-based). + */ endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ endOffset: number; - endPosition?: number; } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ interface CodeFixRequestArgs extends FileRangeRequestArgs { - errorCodes?: ReadonlyArray; + /** + * Errorcodes we want to get the fixes for. + */ + errorCodes: ReadonlyArray; } interface GetCombinedCodeFixRequestArgs { scope: GetCombinedCodeFixScope; @@ -12619,71 +6305,157 @@ declare namespace ts.server.protocol { args: FileRequestArgs; } interface ApplyCodeActionCommandRequestArgs { + /** May also be an array of commands. */ command: {}; } + /** + * Response for GetCodeFixes request. + */ interface GetCodeFixesResponse extends Response { body?: CodeAction[]; } + /** + * A request whose arguments specify a file location (file, line, col). + */ interface FileLocationRequest extends FileRequest { arguments: FileLocationRequestArgs; } + /** + * A request to get codes of supported code fixes. + */ interface GetSupportedCodeFixesRequest extends Request { command: CommandTypes.GetSupportedCodeFixes; } + /** + * A response for GetSupportedCodeFixesRequest request. + */ interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ body?: string[]; } - interface EncodedSemanticClassificationsRequest extends FileRequest { - arguments: EncodedSemanticClassificationsRequestArgs; - } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ start: number; + /** + * Length of the span. + */ length: number; } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ filesToSearch: string[]; } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ interface DefinitionRequest extends FileLocationRequest { command: CommandTypes.Definition; } + interface DefinitionAndBoundSpanRequest extends FileLocationRequest { + readonly command: CommandTypes.DefinitionAndBoundSpan; + } + interface DefinitionAndBoundSpanResponse extends Response { + readonly body: DefinitionInfoAndBoundSpan; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ interface TypeDefinitionRequest extends FileLocationRequest { command: CommandTypes.TypeDefinition; } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ interface ImplementationRequest extends FileLocationRequest { command: CommandTypes.Implementation; } + /** + * Location in source code expressed as (one-based) line and (one-based) column offset. + */ interface Location { line: number; offset: number; } + /** + * Object found in response messages defining a span of text in source code. + */ interface TextSpan { + /** + * First character of the definition. + */ start: Location; + /** + * One character past last character of the definition. + */ end: Location; } + /** + * Object found in response messages defining a span of text in a specific source file. + */ interface FileSpan extends TextSpan { + /** + * File containing text span. + */ file: string; } interface DefinitionInfoAndBoundSpan { definitions: ReadonlyArray; textSpan: TextSpan; } + /** + * Definition response message. Gives text range for definition. + */ interface DefinitionResponse extends Response { body?: FileSpan[]; } interface DefinitionInfoAndBoundSpanReponse extends Response { body?: DefinitionInfoAndBoundSpan; } + /** + * Definition response message. Gives text range for definition. + */ interface TypeDefinitionResponse extends Response { body?: FileSpan[]; } + /** + * Implementation response message. Gives text range for implementations. + */ interface ImplementationResponse extends Response { body?: FileSpan[]; } + /** + * Request to get brace completion for a location in the file. + */ interface BraceCompletionRequest extends FileLocationRequest { command: CommandTypes.BraceCompletion; arguments: BraceCompletionRequestArgs; } + /** + * Argument for BraceCompletionRequest request. + */ interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ openingBrace: string; } interface JsxClosingTagRequest extends FileLocationRequest { @@ -12695,240 +6467,596 @@ declare namespace ts.server.protocol { interface JsxClosingTagResponse extends Response { readonly body: TextInsertion; } + /** + * @deprecated + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ interface OccurrencesRequest extends FileLocationRequest { command: CommandTypes.Occurrences; } + /** @deprecated */ interface OccurrencesResponseItem extends FileSpan { + /** + * True if the occurrence is a write location, false otherwise. + */ isWriteAccess: boolean; + /** + * True if the occurrence is in a string, undefined otherwise; + */ isInString?: true; } + /** @deprecated */ interface OccurrencesResponse extends Response { body?: OccurrencesResponseItem[]; } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ interface DocumentHighlightsRequest extends FileLocationRequest { command: CommandTypes.DocumentHighlights; arguments: DocumentHighlightsRequestArgs; } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + */ interface HighlightSpan extends TextSpan { kind: HighlightSpanKind; } + /** + * Represents a set of highligh spans for a give name + */ interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ file: string; + /** + * Spans to highlight in file. + */ highlightSpans: HighlightSpan[]; } + /** + * Response for a DocumentHighlightsRequest request. + */ interface DocumentHighlightsResponse extends Response { body?: DocumentHighlightsItem[]; } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ interface ReferencesRequest extends FileLocationRequest { command: CommandTypes.References; } interface ReferencesResponseItem extends FileSpan { + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ lineText: string; + /** + * True if reference is a write location, false otherwise. + */ isWriteAccess: boolean; + /** + * True if reference is a definition, false otherwise. + */ isDefinition: boolean; } + /** + * The body of a "references" response message. + */ interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ refs: ReferencesResponseItem[]; + /** + * The name of the symbol. + */ symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ symbolStartOffset: number; + /** + * The full display name of the symbol. + */ symbolDisplayString: string; } + /** + * Response to "references" request. + */ interface ReferencesResponse extends Response { body?: ReferencesResponseBody; } + /** + * Argument for RenameRequest request. + */ interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ findInStrings?: boolean; } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ interface RenameRequest extends FileLocationRequest { command: CommandTypes.Rename; arguments: RenameRequestArgs; } + /** + * Information about the item to be renamed. + */ interface RenameInfo { + /** + * True if item can be renamed. + */ canRename: boolean; + /** + * Error message if item can not be renamed. + */ localizedErrorMessage?: string; + /** + * Display name of the item to be renamed. + */ displayName: string; + /** + * Full display name of item to be renamed. + */ fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers: string; } + /** + * A group of text spans, all in 'file'. + */ interface SpanGroup { + /** The file to which the spans apply */ file: string; + /** The text spans in this group */ locs: TextSpan[]; } interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ locs: ReadonlyArray; } + /** + * Rename response message. + */ interface RenameResponse extends Response { body?: RenameResponseBody; } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicitly. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ interface ExternalFile { + /** + * Name of file file + */ fileName: string; + /** + * Script kind of the file + */ scriptKind?: ScriptKindName | ts.ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ hasMixedContent?: boolean; + /** + * Content of the file + */ content?: string; } + /** + * Represent an external project + */ interface ExternalProject { + /** + * Project name + */ projectFileName: string; + /** + * List of root files in project + */ rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ options: ExternalProjectCompilerOptions; + /** + * @deprecated typingOptions. Use typeAcquisition instead + */ typingOptions?: TypeAcquisition; + /** + * Explicitly specified type acquisition for the project + */ typeAcquisition?: TypeAcquisition; } interface CompileOnSaveMixin { + /** + * If compile on save is enabled for the project + */ compileOnSave?: boolean; } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; - interface ProjectVersionInfo { - projectName: string; - isInferred: boolean; - version: number; - options: ts.CompilerOptions; - languageServiceDisabled: boolean; - lastFileExceededProgramSize?: string; - } + /** + * Represents a set of changes that happen in project + */ interface ProjectChanges { + /** + * List of added files + */ added: string[]; + /** + * List of removed files + */ removed: string[]; + /** + * List of updated files + */ updated: string[]; } - interface ProjectFiles { - info?: ProjectVersionInfo; - files?: string[]; - changes?: ProjectChanges; - } - interface ProjectFilesWithDiagnostics extends ProjectFiles { - projectErrors: DiagnosticWithLinePosition[]; - } - interface ChangedOpenFile { - fileName: string; - changes: ts.TextChange[]; - } + /** + * Information found in a configure request. + */ interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ file?: string; + /** + * The format options to use during formatting and other code editing features. + */ formatOptions?: FormatCodeSettings; preferences?: UserPreferences; + /** + * The host's additional supported .js file extensions + */ extraFileExtensions?: FileExtensionInfo[]; } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ interface ConfigureRequest extends Request { command: CommandTypes.Configure; arguments: ConfigureRequestArguments; } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ interface ConfigureResponse extends Response { } + /** + * Information found in an "open" request. + */ interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ scriptKindName?: ScriptKindName; + /** + * Used to limit the searching for project config file. If given the searching will stop at this + * root path; otherwise it will go all the way up to the dist root path. + */ projectRootPath?: string; } type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ interface OpenRequest extends Request { command: CommandTypes.Open; arguments: OpenRequestArgs; } + /** + * Request to open or update external project + */ interface OpenExternalProjectRequest extends Request { command: CommandTypes.OpenExternalProject; arguments: OpenExternalProjectArgs; } + /** + * Arguments to OpenExternalProjectRequest request + */ type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ interface OpenExternalProjectsRequest extends Request { command: CommandTypes.OpenExternalProjects; arguments: OpenExternalProjectsArgs; } + /** + * Arguments to OpenExternalProjectsRequest + */ interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ projects: ExternalProject[]; } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ interface OpenExternalProjectResponse extends Response { } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ interface OpenExternalProjectsResponse extends Response { } + /** + * Request to close external project. + */ interface CloseExternalProjectRequest extends Request { command: CommandTypes.CloseExternalProject; arguments: CloseExternalProjectRequestArgs; } + /** + * Arguments to CloseExternalProjectRequest request + */ interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ projectFileName: string; } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ interface CloseExternalProjectResponse extends Response { } - interface SynchronizeProjectListRequest extends Request { - arguments: SynchronizeProjectListRequestArgs; - } - interface SynchronizeProjectListRequestArgs { - knownProjects: protocol.ProjectVersionInfo[]; - } - interface ApplyChangedToOpenFilesRequest extends Request { - arguments: ApplyChangedToOpenFilesRequestArgs; - } - interface ApplyChangedToOpenFilesRequestArgs { - openFiles?: ExternalFile[]; - changedFiles?: ChangedOpenFile[]; - closedFiles?: string[]; - } + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ interface SetCompilerOptionsForInferredProjectsRequest extends Request { command: CommandTypes.CompilerOptionsForInferredProjects; arguments: SetCompilerOptionsForInferredProjectsArgs; } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ options: ExternalProjectCompilerOptions; + /** + * Specifies the project root path used to scope compiler options. + * It is an error to provide this property if the server has not been started with + * `useInferredProjectPerProjectRoot` enabled. + */ projectRootPath?: string; } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ interface SetCompilerOptionsForInferredProjectsResponse extends Response { } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ interface ExitRequest extends Request { command: CommandTypes.Exit; } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ interface CloseRequest extends FileRequest { command: CommandTypes.Close; } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ interface CompileOnSaveAffectedFileListRequest extends FileRequest { command: CommandTypes.CompileOnSaveAffectedFileList; } + /** + * Contains a list of files that should be regenerated in a project + */ interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ projectFileName: string; + /** + * List of files names that should be recompiled + */ fileNames: string[]; + /** + * true if project uses outFile or out compiler option + */ projectUsesOutFile: boolean; } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ interface CompileOnSaveAffectedFileListResponse extends Response { body: CompileOnSaveAffectedFileListSingleProject[]; } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ interface CompileOnSaveEmitFileRequest extends FileRequest { command: CommandTypes.CompileOnSaveEmitFile; arguments: CompileOnSaveEmitFileRequestArgs; } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ forced?: boolean; } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ interface QuickInfoRequest extends FileLocationRequest { command: CommandTypes.Quickinfo; } + /** + * Body of QuickInfoResponse. + */ interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers: string; + /** + * Starting file location of symbol. + */ start: Location; + /** + * One past last character of symbol. + */ end: Location; + /** + * Type and kind of symbol. + */ displayString: string; + /** + * Documentation associated with symbol. + */ documentation: string; + /** + * JSDoc tags associated with symbol. + */ tags: JSDocTagInfo[]; } + /** + * Quickinfo response message. + */ interface QuickInfoResponse extends Response { body?: QuickInfoResponseBody; } + /** + * Arguments for format messages. + */ interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ endOffset: number; - endPosition?: number; + /** + * Format options to be used. + */ options?: FormatCodeSettings; } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ interface FormatRequest extends FileLocationRequest { command: CommandTypes.Format; arguments: FormatRequestArgs; } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ interface CodeEdit { + /** + * First character of the text span to edit. + */ start: Location; + /** + * One character past last character of the text span to edit. + */ end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ newText: string; } interface FileCodeEdits { @@ -12936,11 +7064,15 @@ declare namespace ts.server.protocol { textChanges: CodeEdit[]; } interface CodeFixResponse extends Response { + /** The code actions that are available */ body?: CodeFixAction[]; } interface CodeAction { + /** Description of the code action to display in the UI of the editor */ description: string; + /** Text changes to apply to each file as part of the code action */ changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ commands?: {}[]; } interface CombinedCodeActions { @@ -12948,68 +7080,200 @@ declare namespace ts.server.protocol { commands?: ReadonlyArray<{}>; } interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ fixName: string; + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ fixId?: {}; + /** Should be present if and only if 'fixId' is. */ fixAllDescription?: string; } + /** + * Format and format on key response message. + */ interface FormatResponse extends Response { body?: CodeEdit[]; } + /** + * Arguments for format on key messages. + */ interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ key: string; options?: FormatCodeSettings; } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ interface FormatOnKeyRequest extends FileLocationRequest { command: CommandTypes.Formatonkey; arguments: FormatOnKeyRequestArgs; } type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; + /** + * Arguments for completions messages. + */ interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ prefix?: string; + /** + * Character that was responsible for triggering completion. + * Should be `undefined` if a user manually requested completion. + */ triggerCharacter?: CompletionsTriggerCharacter; + /** + * @deprecated Use UserPreferences.includeCompletionsForModuleExports + */ includeExternalModuleExports?: boolean; + /** + * @deprecated Use UserPreferences.includeCompletionsWithInsertText + */ includeInsertTextCompletions?: boolean; } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ interface CompletionsRequest extends FileLocationRequest { command: CommandTypes.Completions; arguments: CompletionsRequestArgs; } + /** + * Arguments for completion details request. + */ interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ entryNames: (string | CompletionEntryIdentifier)[]; } interface CompletionEntryIdentifier { name: string; source?: string; } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ interface CompletionDetailsRequest extends FileLocationRequest { command: CommandTypes.CompletionDetails; arguments: CompletionDetailsRequestArgs; } + /** + * Part of a symbol description. + */ interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ kind: string; } + /** + * An item found in a completion response. + */ interface CompletionEntry { + /** + * The symbol's name. + */ name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers?: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ insertText?: string; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ replacementSpan?: TextSpan; + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ hasAction?: true; + /** + * Identifier (not necessarily human-readable) identifying where this completion came from. + */ source?: string; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ isRecommended?: true; } + /** + * Additional completion entry details, available on demand + */ interface CompletionEntryDetails { + /** + * The symbol's name. + */ name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ documentation?: SymbolDisplayPart[]; + /** + * JSDoc tags for the symbol. + */ tags?: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ codeActions?: CodeAction[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ source?: SymbolDisplayPart[]; } + /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ interface CompletionsResponse extends Response { body?: CompletionEntry[]; } @@ -13025,53 +7289,148 @@ declare namespace ts.server.protocol { interface CompletionDetailsResponse extends Response { body?: CompletionEntryDetails[]; } + /** + * Signature help information for a single parameter + */ interface SignatureHelpParameter { + /** + * The parameter's name + */ name: string; + /** + * Documentation of the parameter. + */ documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ isOptional: boolean; } + /** + * Represents a single signature to show in signature help. + */ interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ isVariadic: boolean; + /** + * The prefix display parts. + */ prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ documentation: SymbolDisplayPart[]; + /** + * The signature's JSDoc tags + */ tags: JSDocTagInfo[]; } + /** + * Signature help items found in the response of a signature help request. + */ interface SignatureHelpItems { + /** + * The signature help items. + */ items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ argumentIndex: number; + /** + * The argument count + */ argumentCount: number; } type SignatureHelpTriggerCharacter = "," | "(" | "<"; type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; + /** + * Arguments of a signature help request. + */ interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + /** + * Reason why signature help was invoked. + * See each individual possible + */ triggerReason?: SignatureHelpTriggerReason; } type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; + /** + * Signals that the user manually requested signature help. + * The language service will unconditionally attempt to provide a result. + */ interface SignatureHelpInvokedReason { kind: "invoked"; triggerCharacter?: undefined; } + /** + * Signals that the signature help request came from a user typing a character. + * Depending on the character and the syntactic context, the request may or may not be served a result. + */ interface SignatureHelpCharacterTypedReason { kind: "characterTyped"; + /** + * Character that was responsible for triggering signature help. + */ triggerCharacter: SignatureHelpTriggerCharacter; } + /** + * Signals that this signature help request came from typing a character or moving the cursor. + * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. + * The language service will unconditionally attempt to provide a result. + * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. + */ interface SignatureHelpRetriggeredReason { kind: "retrigger"; + /** + * Character that was responsible for triggering signature help. + */ triggerCharacter?: SignatureHelpRetriggerCharacter; } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ interface SignatureHelpRequest extends FileLocationRequest { command: CommandTypes.SignatureHelp; arguments: SignatureHelpRequestArgs; } + /** + * Response object for a SignatureHelpRequest. + */ interface SignatureHelpResponse extends Response { body?: SignatureHelpItems; } + /** + * Synchronous request for semantic diagnostics of one file. + */ interface SemanticDiagnosticsSyncRequest extends FileRequest { command: CommandTypes.SemanticDiagnosticsSync; arguments: SemanticDiagnosticsSyncRequestArgs; @@ -13079,6 +7438,9 @@ declare namespace ts.server.protocol { interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { includeLinePosition?: boolean; } + /** + * Response object for synchronous sematic diagnostics request. + */ interface SemanticDiagnosticsSyncResponse extends Response { body?: Diagnostic[] | DiagnosticWithLinePosition[]; } @@ -13088,6 +7450,9 @@ declare namespace ts.server.protocol { } type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; + /** + * Synchronous request for syntactic diagnostics of one file. + */ interface SyntacticDiagnosticsSyncRequest extends FileRequest { command: CommandTypes.SyntacticDiagnosticsSync; arguments: SyntacticDiagnosticsSyncRequestArgs; @@ -13095,26 +7460,68 @@ declare namespace ts.server.protocol { interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { includeLinePosition?: boolean; } + /** + * Response object for synchronous syntactic diagnostics request. + */ interface SyntacticDiagnosticsSyncResponse extends Response { body?: Diagnostic[] | DiagnosticWithLinePosition[]; } + /** + * Arguments for GeterrForProject request. + */ interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ delay: number; } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ interface GeterrForProjectRequest extends Request { command: CommandTypes.GeterrForProject; arguments: GeterrForProjectRequestArgs; } + /** + * Arguments for geterr messages. + */ interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ delay: number; } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ interface GeterrRequest extends Request { command: CommandTypes.Geterr; arguments: GeterrRequestArgs; } type RequestCompletedEventName = "requestCompleted"; + /** + * Event that is sent when server have finished processing request with specified id. + */ interface RequestCompletedEvent extends Event { event: RequestCompletedEventName; body: RequestCompletedEventBody; @@ -13122,38 +7529,103 @@ declare namespace ts.server.protocol { interface RequestCompletedEventBody { request_seq: number; } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ interface Diagnostic { + /** + * Starting file location at which text applies. + */ start: Location; + /** + * The last file location at which the text applies. + */ end: Location; + /** + * Text of diagnostic message. + */ text: string; + /** + * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". + */ category: string; reportsUnnecessary?: {}; + /** + * Any related spans the diagnostic may have, such as other locations relevant to an error, such as declarartion sites + */ relatedInformation?: DiagnosticRelatedInformation[]; + /** + * The error code of the diagnostic message. + */ code?: number; + /** + * The name of the plugin reporting the message. + */ source?: string; } interface DiagnosticWithFileName extends Diagnostic { + /** + * Name of the file the diagnostic is in + */ fileName: string; } + /** + * Represents additional spans returned with a diagnostic which are relevant to it + */ interface DiagnosticRelatedInformation { + /** + * The category of the related information message, e.g. "error", "warning", or "suggestion". + */ category: string; + /** + * The code used ot identify the related information + */ code: number; + /** + * Text of related or additional information. + */ message: string; + /** + * Associated location + */ span?: FileSpan; } interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ file: string; + /** + * An array of diagnostic information items. + */ diagnostics: Diagnostic[]; } type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag"; + /** + * Event message for DiagnosticEventKind event types. + * These events provide syntactic and semantic errors for a file. + */ interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; } interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ triggerFile: string; + /** + * The name of the found config file. + */ configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ diagnostics: DiagnosticWithFileName[]; } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ interface ConfigFileDiagnosticEvent extends Event { body?: ConfigFileDiagnosticEventBody; event: "configFileDiag"; @@ -13164,7 +7636,17 @@ declare namespace ts.server.protocol { body?: ProjectLanguageServiceStateEventBody; } interface ProjectLanguageServiceStateEventBody { + /** + * Project name that has changes in the state of language service. + * For configured projects this will be the config file path. + * For external projects this will be the name of the projects specified when project was open. + * For inferred projects this event is not raised. + */ projectName: string; + /** + * True if language service state switched from disabled to enabled + * and false otherwise. + */ languageServiceEnabled: boolean; } type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; @@ -13173,73 +7655,222 @@ declare namespace ts.server.protocol { body: ProjectsUpdatedInBackgroundEventBody; } interface ProjectsUpdatedInBackgroundEventBody { + /** + * Current set of open files + */ openFiles: string[]; } + type LargeFileReferencedEventName = "largeFileReferenced"; + interface LargeFileReferencedEvent extends Event { + event: LargeFileReferencedEventName; + body: LargeFileReferencedEventBody; + } + interface LargeFileReferencedEventBody { + /** + * name of the large file being loaded + */ + file: string; + /** + * size of the file + */ + fileSize: number; + /** + * max file size allowed on the server + */ + maxFileSize: number; + } + /** + * Arguments for reload request. + */ interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ tmpfile: string; } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ interface ReloadRequest extends FileRequest { command: CommandTypes.Reload; arguments: ReloadRequestArgs; } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ interface ReloadResponse extends Response { } + /** + * Arguments for saveto request. + */ interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ tmpfile: string; } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ interface SavetoRequest extends FileRequest { command: CommandTypes.Saveto; arguments: SavetoRequestArgs; } + /** + * Arguments for navto request message. + */ interface NavtoRequestArgs extends FileRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ searchValue: string; + /** + * Optional limit on the number of items to return. + */ maxResultCount?: number; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ currentFileOnly?: boolean; projectFileName?: string; } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ interface NavtoRequest extends FileRequest { command: CommandTypes.Navto; arguments: NavtoRequestArgs; } + /** + * An item found in a navto response. + */ interface NavtoItem extends FileSpan { + /** + * The symbol's name. + */ name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ kind: ScriptElementKind; + /** + * exact, substring, or prefix. + */ matchKind: string; + /** + * If this was a case sensitive or insensitive match. + */ isCaseSensitive: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers?: string; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ containerKind?: ScriptElementKind; } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ interface NavtoResponse extends Response { body?: NavtoItem[]; } + /** + * Arguments for change request message. + */ interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ insertString?: string; } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ interface ChangeRequest extends FileLocationRequest { command: CommandTypes.Change; arguments: ChangeRequestArgs; } + /** + * Response to "brace" request. + */ interface BraceResponse extends Response { body?: TextSpan[]; } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ interface BraceRequest extends FileLocationRequest { command: CommandTypes.Brace; } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ interface NavBarRequest extends FileRequest { command: CommandTypes.NavBar; } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ interface NavTreeRequest extends FileRequest { command: CommandTypes.NavTree; } interface NavigationBarItem { + /** + * The item's display text. + */ text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ kindModifiers?: string; + /** + * The definition locations of the item. + */ spans: TextSpan[]; + /** + * Optional children. + */ childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ indent: number; } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ interface NavigationTree { text: string; kind: ScriptElementKind; @@ -13271,8 +7902,17 @@ declare namespace ts.server.protocol { payload: TypingsInstalledTelemetryEventPayload; } interface TypingsInstalledTelemetryEventPayload { + /** + * Comma separated list of installed typing packages + */ installedPackages: string; + /** + * true if install request succeeded, otherwise - false + */ installSuccess: boolean; + /** + * version of typings installer + */ typingsInstallerVersion: string; } type BeginInstallTypesEventName = "beginInstallTypes"; @@ -13286,12 +7926,21 @@ declare namespace ts.server.protocol { body: EndInstallTypesEventBody; } interface InstallTypesEventBody { + /** + * correlation id to match begin and end events + */ eventId: number; + /** + * list of packages to install + */ packages: ReadonlyArray; } interface BeginInstallTypesEventBody extends InstallTypesEventBody { } interface EndInstallTypesEventBody extends InstallTypesEventBody { + /** + * true if installation succeeded, otherwise false + */ success: boolean; } interface NavBarResponse extends Response { @@ -13334,7 +7983,15 @@ declare namespace ts.server.protocol { interface UserPreferences { readonly disableSuggestions?: boolean; readonly quotePreference?: "double" | "single"; + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ readonly includeCompletionsForModuleExports?: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; @@ -13406,6 +8063,7 @@ declare namespace ts.server.protocol { traceResolution?: boolean; resolveJsonModule?: boolean; types?: string[]; + /** Paths used to used to compute primary types search locations */ typeRoots?: string[]; [option: string]: CompilerOptionsValue | undefined; } @@ -13448,65 +8106,25 @@ declare namespace ts.server { svc: number; text: number; } - class TextStorage { - private readonly host; - private readonly fileName; - version: ScriptInfoVersion; - private svc; - private text; - private lineMap; - isOpen: boolean; - private ownFileText; - private pendingReloadFromDisk; - constructor(host: ServerHost, fileName: NormalizedPath, initialVersion?: ScriptInfoVersion); - getVersion(): string; - hasScriptVersionCache_TestOnly(): boolean; - useScriptVersionCache_TestOnly(): void; - useText(newText?: string): void; - edit(start: number, end: number, newText: string): void; - reload(newText: string): true | undefined; - reloadWithFileText(tempFileName?: string): true | undefined; - reloadFromDisk(): boolean | undefined; - delayReloadFromFileIntoText(): void; - getSnapshot(): IScriptSnapshot; - getLineInfo(line: number): AbsolutePositionAndLineText; - lineToTextSpan(line: number): TextSpan; - lineOffsetToPosition(line: number, offset: number): number; - positionToLineOffset(position: number): protocol.Location; - private getFileText; - private switchToScriptVersionCache; - private useScriptVersionCacheIfValidOrOpen; - private getOrLoadText; - private getLineMap; - } - function isDynamicFileName(fileName: NormalizedPath): boolean; - interface DocumentRegistrySourceFileCache { - key: DocumentRegistryBucketKey; - sourceFile: SourceFile; - } class ScriptInfo { private readonly host; readonly fileName: NormalizedPath; readonly scriptKind: ScriptKind; readonly hasMixedContent: boolean; readonly path: Path; + /** + * All projects that include this file + */ readonly containingProjects: Project[]; private formatSettings; private preferences; - fileWatcher: FileWatcher | undefined; private textStorage; - readonly isDynamic: boolean; - private realpath; - cacheSourceFile: DocumentRegistrySourceFileCache; constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path, initialVersion?: ScriptInfoVersion); - getVersion(): ScriptInfoVersion; - isDynamicOrHasMixedContent(): boolean; isScriptOpen(): boolean; open(newText: string): void; close(fileExists?: boolean): void; getSnapshot(): IScriptSnapshot; private ensureRealPath; - getRealpathIfDifferent(): Path | undefined; getFormatCodeSettings(): FormatCodeSettings | undefined; getPreferences(): UserPreferences | undefined; attachToProject(project: Project): boolean; @@ -13518,13 +8136,18 @@ declare namespace ts.server { setOptions(formatSettings: FormatCodeSettings, preferences: UserPreferences | undefined): void; getLatestVersion(): string; saveTo(fileName: string): void; - delayReloadNonMixedContentFile(): void; - reloadFromFile(tempFileName?: NormalizedPath): void; - getLineInfo(line: number): AbsolutePositionAndLineText; + reloadFromFile(tempFileName?: NormalizedPath): boolean; editContent(start: number, end: number, newText: string): void; markContainingProjectsAsDirty(): void; isOrphan(): boolean; + /** + * @param line 1 based index + */ lineToTextSpan(line: number): TextSpan; + /** + * @param line 1 based index + * @param offset 1 based index + */ lineOffsetToPosition(line: number, offset: number): number; positionToLineOffset(position: number): protocol.Location; isJavaScript(): boolean; @@ -13544,16 +8167,6 @@ declare namespace ts.server { readonly globalTypingsCacheLocation: string | undefined; } const nullTypingsInstaller: ITypingsInstaller; - class TypingsCache { - private readonly installer; - private readonly perProjectCache; - constructor(installer: ITypingsInstaller); - isKnownTypesPackageName(name: string): boolean; - installPackage(options: InstallPackageOptionsWithProject): Promise; - enqueueInstallTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray | undefined, forceRefresh: boolean): void; - updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, newTypings: string[]): SortedReadonlyArray | SortedArray; - onProjectClosed(project: Project): void; - } } declare namespace ts.server { enum ProjectKind { @@ -13561,16 +8174,8 @@ declare namespace ts.server { Configured = 1, External = 2 } - type Mutable = { - -readonly [K in keyof T]: T[K]; - }; - function countEachFileTypes(infos: ScriptInfo[]): FileStats; function allRootFilesAreJsOrDts(project: Project): boolean; function allFilesAreJsOrDts(project: Project): boolean; - function hasNoTypeScriptSource(fileNames: string[]): boolean; - interface ProjectFilesWithTSDiagnostics extends protocol.ProjectFiles { - projectErrors: ReadonlyArray; - } interface PluginCreateInfo { project: Project; languageService: LanguageService; @@ -13585,8 +8190,11 @@ declare namespace ts.server { type PluginModuleFactory = (mod: { typescript: typeof ts; }) => PluginModule; + /** + * The project root can be script info - if root is present, + * or it could be just normalized path if root wasnt present on the host(only for non inferred project) + */ type ProjectRoot = ScriptInfo | NormalizedPath; - function isScriptInfo(value: ProjectRoot): value is ScriptInfo; abstract class Project implements LanguageServiceHost, ModuleResolutionHost { readonly projectName: string; readonly projectKind: ProjectKind; @@ -13600,33 +8208,40 @@ declare namespace ts.server { private externalFiles; private missingFilesMap; private plugins; - cachedUnresolvedImportsPerFile: Map>; - lastCachedUnresolvedImportsList: SortedReadonlyArray | undefined; - private hasAddedorRemovedFiles; private lastFileExceededProgramSize; protected languageService: LanguageService; languageServiceEnabled: boolean; readonly trace?: (s: string) => void; readonly realpath?: (path: string) => string; - hasInvalidatedResolution: HasInvalidatedResolution; - resolutionCache: ResolutionCache; private builderState; + /** + * Set of files names that were updated since the last call to getChangesSinceVersion. + */ private updatedFileNames; + /** + * Set of files that was returned from the last call to getChangesSinceVersion. + */ private lastReportedFileNames; + /** + * Last version that was reported. + */ private lastReportedVersion; + /** + * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one) + * This property is changed in 'updateGraph' based on the set of files in program + */ private projectProgramVersion; + /** + * Current version of the project state. It is changed when: + * - new root file was added/removed + * - edit happen in some file that is currently included in the project. + * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project + */ private projectStateVersion; - dirty: boolean; - hasChangedAutomaticTypeDirectiveNames: boolean; - typingFiles: SortedReadonlyArray; private readonly cancellationToken; isNonTsProject(): boolean; isJsOnlyProject(): boolean; static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined; - readonly currentDirectory: string; - directoryStructureHost: DirectoryStructureHost; - readonly getCanonicalFileName: GetCanonicalFileName; - constructor(projectName: string, projectKind: ProjectKind, projectService: ProjectService, documentRegistry: DocumentRegistry, hasExplicitListOfFiles: boolean, lastFileExceededProgramSize: string | undefined, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean, directoryStructureHost: DirectoryStructureHost, currentDirectory: string | undefined); isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptions): Promise; private readonly typingsCache; @@ -13634,7 +8249,7 @@ declare namespace ts.server { getCompilerOptions(): CompilerOptions; getNewLine(): string; getProjectVersion(): string; - getProjectReferences(): ReadonlyArray | undefined; + getProjectReferences(): ReadonlyArray; getScriptFileNames(): string[]; private getOrCreateScriptInfoAndAttachToProject; getScriptKind(fileName: string): ScriptKind; @@ -13652,22 +8267,20 @@ declare namespace ts.server { resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists(path: string): boolean; getDirectories(path: string): string[]; - getCachedDirectoryStructureHost(): CachedDirectoryStructureHost; - toPath(fileName: string): Path; - watchDirectoryOfFailedLookupLocation(directory: string, cb: DirectoryWatcherCallback, flags: WatchDirectoryFlags): FileWatcher; - onInvalidatedResolution(): void; - watchTypeRootsDirectory(directory: string, cb: DirectoryWatcherCallback, flags: WatchDirectoryFlags): FileWatcher; - onChangedAutomaticTypeDirectiveNames(): void; - getGlobalCache(): string | undefined; - writeLog(s: string): void; log(s: string): void; error(s: string): void; private setInternalCompilerOptionsForEmittingJsFiles; + /** + * Get the errors that dont have any file name associated + */ getGlobalProjectErrors(): ReadonlyArray; getAllProjectErrors(): ReadonlyArray; getLanguageService(ensureSynchronized?: boolean): LanguageService; private shouldEmitFile; getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; + /** + * Returns true if emit was conducted + */ emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; enableLanguageService(): void; disableLanguageService(lastFileExceededProgramSize?: string): void; @@ -13676,14 +8289,11 @@ declare namespace ts.server { protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; getExternalFiles(): SortedReadonlyArray; getSourceFile(path: Path): SourceFile | undefined; - getSourceFileOrConfigFile(path: Path): SourceFile | undefined; close(): void; private detachScriptInfoIfNotRoot; isClosed(): boolean; hasRoots(): boolean; - isOrphan(): boolean; getRootFiles(): NormalizedPath[]; - getRootFilesMap(): Map; getRootScriptInfos(): ScriptInfo[]; getScriptInfos(): ScriptInfo[]; getExcludedFiles(): ReadonlyArray; @@ -13697,11 +8307,11 @@ declare namespace ts.server { removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void; registerFileUpdate(fileName: string): void; markAsDirty(): void; - private extractUnresolvedImportsFromSourceFile; - onFileAddedOrRemoved(): void; + /** + * Updates set of files that contribute to this project + * @returns: true if set of files in the project stays the same and false - otherwise. + */ updateGraph(): boolean; - updateTypingFiles(typingFiles: SortedReadonlyArray): void; - getCurrentProgram(): Program; protected removeExistingTypings(include: string[]): string[]; private updateGraphWorker; private detachScriptInfoFromProject; @@ -13711,66 +8321,76 @@ declare namespace ts.server { getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; - getChangesSinceVersion(lastKnownVersion?: number): ProjectFilesWithTSDiagnostics; protected removeRoot(info: ScriptInfo): void; protected enableGlobalPlugins(): void; protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ refreshDiagnostics(): void; private enableProxy; } + /** + * If a file is opened and no tsconfig (or jsconfig) is found, + * the file and its imports/references are put into an InferredProject. + */ class InferredProject extends Project { private static readonly newName; private _isJsInferredProject; toggleJsInferredProject(isJsInferredProject: boolean): void; setCompilerOptions(options?: CompilerOptions): void; + /** this is canonical project root path */ readonly projectRootPath: string | undefined; - readonly canonicalCurrentDirectory: string | undefined; - constructor(projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, projectRootPath: NormalizedPath | undefined, currentDirectory: string | undefined); addRoot(info: ScriptInfo): void; removeRoot(info: ScriptInfo): void; - isOrphan(): boolean; isProjectWithSingleRoot(): boolean; close(): void; getTypeAcquisition(): TypeAcquisition; } + /** + * If a file is opened, the server will look for a tsconfig (or jsconfig) + * and if successfull create a ConfiguredProject for it. + * Otherwise it will create an InferredProject. + */ class ConfiguredProject extends Project { compileOnSaveEnabled: boolean; private projectReferences; private typeAcquisition; - configFileWatcher: FileWatcher | undefined; private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; - pendingReload: ConfigFileProgramReloadLevel; - configFileSpecs: ConfigFileSpecs | undefined; + /** Ref count to the project when opened from external project */ private externalProjectRefCount; private projectErrors; - constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: DocumentRegistry, hasExplicitListOfFiles: boolean, compilerOptions: CompilerOptions, lastFileExceededProgramSize: string | undefined, compileOnSaveEnabled: boolean, cachedDirectoryStructureHost: CachedDirectoryStructureHost, projectReferences: ReadonlyArray | undefined); + /** + * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph + * @returns: true if set of files in the project stays the same and false - otherwise. + */ updateGraph(): boolean; - getCachedDirectoryStructureHost(): CachedDirectoryStructureHost; getConfigFilePath(): NormalizedPath; - getProjectReferences(): ReadonlyArray | undefined; + getProjectReferences(): ReadonlyArray; updateReferences(refs: ReadonlyArray | undefined): void; enablePlugins(): void; + /** + * Get the errors that dont have any file name associated + */ getGlobalProjectErrors(): ReadonlyArray; + /** + * Get all the project errors + */ getAllProjectErrors(): ReadonlyArray; setProjectErrors(projectErrors: Diagnostic[]): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; getTypeAcquisition(): TypeAcquisition; - watchWildcards(wildcardDirectories: Map): void; - stopWatchingWildCards(): void; close(): void; - addExternalProjectReference(): void; - deleteExternalProjectReference(): void; - hasOpenRef(): boolean; getEffectiveTypeRoots(): string[]; - updateErrorOnNoInputFiles(hasFileNames: boolean): void; } + /** + * Project whose configuration is handled externally, such as in a '.csproj'. + * These are created only if a host explicitly calls `openExternalProject`. + */ class ExternalProject extends Project { externalProjectName: string; compileOnSaveEnabled: boolean; excludedFiles: ReadonlyArray; private typeAcquisition; - constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, lastFileExceededProgramSize: string | undefined, compileOnSaveEnabled: boolean, projectFilePath?: string); getExcludedFiles(): ReadonlyArray; getTypeAcquisition(): TypeAcquisition; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; @@ -13779,6 +8399,7 @@ declare namespace ts.server { declare namespace ts.server { const maxProgramSizeForNonTsFiles: number; const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + const LargeFileReferencedEvent = "largeFileReferenced"; const ConfigFileDiagEvent = "configFileDiag"; const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; const ProjectInfoTelemetryEvent = "projectInfo"; @@ -13789,6 +8410,14 @@ declare namespace ts.server { openFiles: string[]; }; } + interface LargeFileReferencedEvent { + eventName: typeof LargeFileReferencedEvent; + data: { + file: string; + fileSize: number; + maxFileSize: number; + }; + } interface ConfigFileDiagEvent { eventName: typeof ConfigFileDiagEvent; data: { @@ -13804,13 +8433,20 @@ declare namespace ts.server { languageServiceEnabled: boolean; }; } + /** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */ interface ProjectInfoTelemetryEvent { readonly eventName: typeof ProjectInfoTelemetryEvent; readonly data: ProjectInfoTelemetryEventData; } interface ProjectInfoTelemetryEventData { + /** Cryptographically secure hash of project file location. */ readonly projectId: string; + /** Count of file extensions seen in the project. */ readonly fileStats: FileStats; + /** + * Any compiler options that might contain paths will be taken out. + * Enum compiler options will be converted to strings. + */ readonly compilerOptions: CompilerOptions; readonly extends: boolean | undefined; readonly files: boolean | undefined; @@ -13821,8 +8457,14 @@ declare namespace ts.server { readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other"; readonly projectType: "external" | "configured"; readonly languageServiceEnabled: boolean; + /** TypeScript version used by the server. */ readonly version: string; } + /** + * Info that we may send about a file that was just opened. + * Info about a file will only be sent once per session, even if the file changes in ways that might affect the info. + * Currently this is only sent for '.js' files. + */ interface OpenFileInfoTelemetryEvent { readonly eventName: typeof OpenFileInfoTelemetryEvent; readonly data: OpenFileInfoTelemetryEventData; @@ -13846,7 +8488,7 @@ declare namespace ts.server { interface OpenFileInfo { readonly checkJs: boolean; } - type ProjectServiceEvent = ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; interface SafeList { [name: string]: { @@ -13875,20 +8517,6 @@ declare namespace ts.server { configFileName?: NormalizedPath; configFileErrors?: ReadonlyArray; } - enum WatchType { - ConfigFilePath = "Config file for the program", - MissingFilePath = "Missing file from program", - WildcardDirectories = "Wild card directory", - ClosedScriptInfo = "Closed Script info", - ConfigFileForInferredRoot = "Config file for the inferred project root", - FailedLookupLocation = "Directory of Failed lookup locations in module resolution", - TypeRoots = "Type root directory" - } - interface ConfigFileExistenceInfo { - exists: boolean; - openFilesImpactedByConfigFile: Map; - configFileWatcherForRootOfInferredProject?: FileWatcher; - } interface ProjectServiceOptions { host: ServerHost; logger: Logger; @@ -13906,28 +8534,60 @@ declare namespace ts.server { syntaxOnly?: boolean; } class ProjectService { - readonly typingsCache: TypingsCache; - readonly documentRegistry: DocumentRegistry; + /** + * Container of all known scripts + */ private readonly filenameToScriptInfo; + /** + * Contains all the deleted script info's version information so that + * it does not reset when creating script info again + * (and could have potentially collided with version where contents mismatch) + */ private readonly filenameToScriptInfoVersion; private readonly allJsFilesForOpenFileTelemetry; - readonly realpathToScriptInfos: MultiMap | undefined; + /** + * maps external project file name to list of config files that were the part of this project + */ private readonly externalProjectToConfiguredProjectMap; + /** + * external projects (configuration and list of root files is not controlled by tsserver) + */ readonly externalProjects: ExternalProject[]; + /** + * projects built from openFileRoots + */ readonly inferredProjects: InferredProject[]; + /** + * projects specified by a tsconfig.json file + */ readonly configuredProjects: Map; + /** + * Open files: with value being project root path, and key being Path of the file that is open + */ readonly openFiles: Map; + /** + * Map of open files that are opened without complete path but have projectRoot as current directory + */ private readonly openFilesWithNonRootedDiskPath; private compilerOptionsForInferredProjects; private compilerOptionsForInferredProjectsPerProjectRoot; + /** + * Project size for configured or external projects + */ private readonly projectToSizeMap; + /** + * This is a map of config file paths existance that doesnt need query to disk + * - The entry can be present because there is inferred project that needs to watch addition of config file to directory + * In this case the exists could be true/false based on config file is present or not + * - Or it is present if we have configured project open with config file at that location + * In this case the exists property is always true + */ private readonly configFileExistenceInfoCache; private readonly throttledOperations; private readonly hostConfiguration; private safelist; private legacySafelist; private pendingProjectUpdates; - pendingEnsureProjectForOpenFiles: boolean; readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; readonly host: ServerHost; @@ -13945,34 +8605,27 @@ declare namespace ts.server { readonly allowLocalPluginLoads: boolean; readonly typesMapLocation: string | undefined; readonly syntaxOnly?: boolean; + /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects; - readonly watchFactory: WatchFactory; constructor(opts: ProjectServiceOptions); toPath(fileName: string): Path; - getExecutingFilePath(): string; - getNormalizedAbsolutePath(fileName: string): string; - setDocument(key: DocumentRegistryBucketKey, path: Path, sourceFile: SourceFile): void; - getDocument(key: DocumentRegistryBucketKey, path: Path): SourceFile | undefined; - ensureInferredProjectsUpToDate_TestOnly(): void; - getCompilerOptionsForInferredProjects(): CompilerOptions; - onUpdateLanguageServiceStateForProject(project: Project, languageServiceEnabled: boolean): void; private loadTypesMap; updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; - updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse | BeginInstallTypes | EndInstallTypes): void; private delayEnsureProjectForOpenFiles; private delayUpdateProjectGraph; - hasPendingProjectUpdate(project: Project): boolean; - sendProjectsUpdatedInBackgroundEvent(): void; - delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project: Project): void; private delayUpdateProjectGraphs; setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void; findProject(projectName: string): Project | undefined; - forEachProject(cb: (project: Project) => void): void; getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined; - tryGetDefaultProjectForFile(fileName: NormalizedPath): Project | undefined; - ensureDefaultProjectForFile(fileName: NormalizedPath): Project; private doEnsureDefaultProjectForFile; getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined; + /** + * Ensures the project structures are upto date + * This means, + * - we go through all the projects and update them if they are dirty + * - if updates reflect some change in structure or there was pending request to ensure projects for open files + * ensure that each open script info has project + */ private ensureProjectStructuresUptoDate; getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; getPreferences(file: NormalizedPath): UserPreferences; @@ -13980,31 +8633,67 @@ declare namespace ts.server { getHostPreferences(): UserPreferences; private onSourceFileChanged; private handleDeletedFile; - watchWildcardDirectory(directory: Path, flags: WatchDirectoryFlags, project: ConfiguredProject): FileWatcher; - getConfigFileExistenceInfo(project: ConfiguredProject): ConfigFileExistenceInfo; private onConfigChangedForConfiguredProject; + /** + * This is the callback function for the config file add/remove/change at any location + * that matters to open script info but doesnt have configured project open + * for the config file + */ private onConfigFileChangeForOpenScriptInfo; private removeProject; - assignOrphanScriptInfoToInferredProject(info: ScriptInfo, projectRootPath: NormalizedPath | undefined): InferredProject; + /** + * Remove this file from the set of open, non-configured files. + * @param info The file that has been closed or newly configured + */ private closeOpenFile; private deleteScriptInfo; private configFileExists; private setConfigFileExistenceByNewConfiguredProject; + /** + * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project + */ private configFileExistenceImpactsRootOfInferredProject; private setConfigFileExistenceInfoByClosedConfiguredProject; private logConfigFileWatchUpdate; + /** + * Create the watcher for the configFileExistenceInfo + */ private createConfigFileWatcherOfConfigFileExistence; + /** + * Close the config file watcher in the cached ConfigFileExistenceInfo + * if there arent any open files that are root of inferred project + */ private closeConfigFileWatcherOfConfigFileExistenceInfo; + /** + * This is called on file close, so that we stop watching the config file for this script info + */ private stopWatchingConfigFilesForClosedScriptInfo; - startWatchingConfigFilesForInferredProjectRoot(info: ScriptInfo): void; - stopWatchingConfigFilesForInferredProjectRoot(info: ScriptInfo): void; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ private forEachConfigFileLocation; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + * If script info is passed in, it is asserted to be open script info + * otherwise just file name + */ private getConfigFileNameForFile; private printProjects; private findConfiguredProjectByProjectName; private getConfiguredProjectByCanonicalConfigFilePath; private findExternalProjectByProjectName; private convertConfigFileContentToProjectOptions; + /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ private getFilenameForExceededTotalSizeLimitForNonTsFiles; private createExternalProject; private sendProjectTelemetry; @@ -14012,45 +8701,73 @@ declare namespace ts.server { private createConfiguredProject; private updateNonInferredProjectFiles; private updateNonInferredProject; - reloadFileNamesOfConfiguredProject(project: ConfiguredProject): boolean; - reloadConfiguredProject(project: ConfiguredProject): void; private sendConfigFileDiagEvent; private getOrCreateInferredProjectForProjectRootPathIfEnabled; private getOrCreateSingleInferredProjectIfEnabled; private getOrCreateSingleInferredWithoutProjectRoot; private createInferredProject; - getOrCreateScriptInfoNotOpenedByClient(uncheckedFileName: string, currentDirectory: string, hostToQueryFileExistsOn: DirectoryStructureHost): ScriptInfo | undefined; getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; - getSymlinkedProjects(info: ScriptInfo): MultiMap | undefined; private watchClosedScriptInfo; private stopWatchingScriptInfo; - getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName: NormalizedPath, currentDirectory: string, scriptKind: ScriptKind | undefined, hasMixedContent: boolean | undefined, hostToQueryFileExistsOn: DirectoryStructureHost | undefined): ScriptInfo | undefined; - getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName: NormalizedPath, currentDirectory: string, fileContent: string | undefined, scriptKind: ScriptKind | undefined, hasMixedContent: boolean | undefined): ScriptInfo | undefined; + private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; + private getOrCreateScriptInfoOpenedByClientForNormalizedPath; getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { fileExists(path: string): boolean; }): ScriptInfo | undefined; private getOrCreateScriptInfoWorker; + /** + * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred + */ getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; getScriptInfoForPath(fileName: Path): ScriptInfo | undefined; setHostConfiguration(args: protocol.ConfigureRequestArguments): void; closeLog(): void; + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ reloadProjects(): void; private delayReloadConfiguredProjectForFiles; + /** + * This function goes through all the openFiles and tries to file the config file for them. + * If the config file is found and it refers to existing project, it reloads it either immediately + * or schedules it for reload depending on delayReload option + * If the there is no existing project it just opens the configured project for the config file + * reloadForInfo provides a way to filter out files to reload configured project for + */ private reloadConfiguredProjectForFiles; + /** + * Remove the root of inferred project if script info is part of another project + */ private removeRootOfInferredProjectIfNowPartOfOtherProject; + /** + * This function is to update the project structure for every inferred project. + * It is called on the premise that all the configured projects are + * up to date. + * This will go through open files and assign them to inferred project if open file is not part of any other project + * After that all the inferred project graphs are updated + */ private ensureProjectForOpenFiles; + /** + * Open file whose contents is managed by the client + * @param filename is absolute pathname + * @param fileContent is a known version of the file content that is more up to date than the one on disk + */ openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; private findExternalProjectContainingOpenScriptInfo; openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; + private removeOrphanConfiguredProjects; private telemetryOnOpenFile; + /** + * Close file whose contents is managed by the client + * @param filename is absolute pathname + */ closeClientFile(uncheckedFileName: string): void; private collectChanges; - synchronizeProjectList(knownProjects: protocol.ProjectVersionInfo[]): ProjectFilesWithTSDiagnostics[]; - applyChangesInOpenFiles(openFiles: protocol.ExternalFile[] | undefined, changedFiles: protocol.ChangedOpenFile[] | undefined, closedFiles: string[] | undefined): void; - applyChangesToFile(scriptInfo: ScriptInfo, changes: TextChange[]): void; private closeConfiguredProjectReferencedFromExternalProject; closeExternalProject(uncheckedFileName: string): void; openExternalProjects(projects: protocol.ExternalProject[]): void; + /** Makes a filename safe to insert in a RegExp */ private static readonly filenameEscapeRegexp; private static escapeFilenameForRegex; resetSafeList(): void; @@ -14076,7 +8793,6 @@ declare namespace ts.server { interface EventSender { event: Event; } - function toEvent(eventName: string, body: object): protocol.Event; interface SessionOptions { host: ServerHost; cancellationToken: ServerCancellationToken; @@ -14086,8 +8802,12 @@ declare namespace ts.server { byteLength: (buf: string, encoding?: string) => number; hrtime: (start?: number[]) => number[]; logger: Logger; + /** + * If falsy, all events are suppressed. + */ canUseEvents: boolean; eventHandler?: ProjectServiceEventHandler; + /** Has no effect if eventHandler is also specified. */ suppressDiagnosticEvents?: boolean; syntaxOnly?: boolean; throttleWaitMilliseconds?: number; @@ -14119,12 +8839,14 @@ declare namespace ts.server { logError(err: Error, cmd: string): void; send(msg: protocol.Message): void; event(body: T, eventName: string): void; + /** @deprecated */ output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; private doOutput; private semanticCheck; private syntacticCheck; private suggestionCheck; private sendDiagnosticsEvent; + /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ private updateErrorCheck; private cleanProjects; private cleanup; @@ -14137,11 +8859,14 @@ declare namespace ts.server { private convertToDiagnosticsWithLinePosition; private getDiagnosticsWorker; private getDefinition; + private mapDefinitionInfoLocations; private getDefinitionAndBoundSpan; + private getEmitOutput; private mapDefinitionInfo; private static mapToOriginalLocation; private toFileSpan; private getTypeDefinition; + private mapImplementationLocations; private getImplementation; private getOccurrences; private getSyntacticDiagnosticsSync; @@ -14156,7 +8881,13 @@ declare namespace ts.server { private getProjects; private getDefaultProject; private getRenameLocations; + private static mapRenameInfo; + private toSpanGroups; private getReferences; + /** + * @param fileName is the name of the file to be opened + * @param fileContent is a version of the file content that is known to be more up to date than the one on disk + */ private openClientFile; private getPosition; private getPositionInFile; @@ -14194,6 +8925,7 @@ declare namespace ts.server { private toLocationTextSpan; private getNavigationTree; private getNavigateToItems; + private getFullNavigateToItems; private getSupportedCodeFixes; private isLocation; private extractPositionAndRange; @@ -14232,110 +8964,7 @@ declare namespace ts.server { response?: {}; responseRequired?: boolean; } - function getLocationInNewDocument(oldText: string, renameFilename: string, renameLocation: number, edits: ReadonlyArray): protocol.Location; -} -declare namespace ts.server { - interface LineCollection { - charCount(): number; - lineCount(): number; - isLeaf(): this is LineLeaf; - walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker): void; - } - interface AbsolutePositionAndLineText { - absolutePosition: number; - lineText: string | undefined; - } - enum CharRangeSection { - PreStart = 0, - Start = 1, - Entire = 2, - Mid = 3, - End = 4, - PostEnd = 5 - } - interface LineIndexWalker { - goSubtree: boolean; - done: boolean; - leaf(relativeStart: number, relativeLength: number, lineCollection: LineLeaf): void; - pre?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): void; - post?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): void; - } - class ScriptVersionCache { - private changes; - private readonly versions; - private minVersion; - private currentVersion; - private static readonly changeNumberThreshold; - private static readonly changeLengthThreshold; - private static readonly maxVersions; - private versionToIndex; - private currentVersionToIndex; - edit(pos: number, deleteLen: number, insertedText?: string): void; - getSnapshot(): IScriptSnapshot; - private _getSnapshot; - getSnapshotVersion(): number; - getLineInfo(line: number): AbsolutePositionAndLineText; - lineOffsetToPosition(line: number, column: number): number; - positionToLineOffset(position: number): protocol.Location; - lineToTextSpan(line: number): TextSpan; - getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange | undefined; - static fromString(script: string): ScriptVersionCache; - } - class LineIndex { - root: LineNode; - checkEdits: boolean; - absolutePositionOfStartOfLine(oneBasedLine: number): number; - positionToLineOffset(position: number): protocol.Location; - private positionToColumnAndLineText; - lineNumberToInfo(oneBasedLine: number): AbsolutePositionAndLineText; - load(lines: string[]): void; - walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker): void; - getText(rangeStart: number, rangeLength: number): string; - getLength(): number; - every(f: (ll: LineLeaf, s: number, len: number) => boolean, rangeStart: number, rangeEnd?: number): boolean; - edit(pos: number, deleteLength: number, newText?: string): LineIndex; - private static buildTreeFromBottom; - static linesFromText(text: string): { - lines: string[]; - lineMap: number[]; - }; - } - class LineNode implements LineCollection { - private readonly children; - totalChars: number; - totalLines: number; - constructor(children?: LineCollection[]); - isLeaf(): boolean; - updateCounts(): void; - private execWalk; - private skipChild; - walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker): void; - charOffsetToLineInfo(lineNumberAccumulator: number, relativePosition: number): { - oneBasedLine: number; - zeroBasedColumn: number; - lineText: string | undefined; - }; - lineNumberToInfo(relativeOneBasedLine: number, positionAccumulator: number): { - position: number; - leaf: LineLeaf | undefined; - }; - private splitAfter; - remove(child: LineCollection): void; - private findChildIndex; - insertAt(child: LineCollection, nodes: LineCollection[]): LineNode[]; - add(collection: LineCollection): void; - charCount(): number; - lineCount(): number; - } - class LineLeaf implements LineCollection { - text: string; - constructor(text: string); - isLeaf(): boolean; - walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker): void; - charCount(): number; - lineCount(): number; - } } -//# sourceMappingURL=server.d.ts.map + export = ts; export as namespace ts; \ No newline at end of file diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 7b357e89a6e8e..19046c62c9ab7 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1,113 +1,93 @@ -"use strict";"use strict"; -/*@internal*/ -var ts; -(function (ts) { - /** Gets a timestamp with (at least) ms resolution */ - ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; -})(ts || (ts = {})); -/*@internal*/ -/** Performance measurements for the compiler. */ -(function (ts) { - var performance; - (function (performance) { - // NOTE: cannot use ts.noop as core.ts loads after this - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; - var enabled = false; - var profilerStart = 0; - var counts; - var marks; - var measures; - /** - * Marks a performance event. - * - * @param markName The name of the mark. - */ - function mark(markName) { - if (enabled) { - marks.set(markName, ts.timestamp()); - counts.set(markName, (counts.get(markName) || 0) + 1); - profilerEvent(markName); - } +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - performance.mark = mark; - /** - * Adds a performance measurement with the specified name. - * - * @param measureName The name of the performance measurement. - * @param startMarkName The name of the starting mark. If not supplied, the point at which the - * profiler was enabled is used. - * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is - * used. - */ - function measure(measureName, startMarkName, endMarkName) { - if (enabled) { - var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); - var start = startMarkName && marks.get(startMarkName) || profilerStart; - measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + return t; + }; + return __assign.apply(this, arguments); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; } - } - performance.measure = measure; - /** - * Gets the number of times a marker was encountered. - * - * @param markName The name of the mark. - */ - function getCount(markName) { - return counts && counts.get(markName) || 0; - } - performance.getCount = getCount; - /** - * Gets the total duration of all measurements with the supplied name. - * - * @param measureName The name of the measure whose durations should be accumulated. - */ - function getDuration(measureName) { - return measures && measures.get(measureName) || 0; - } - performance.getDuration = getDuration; - /** - * Iterate over each measure, performing some action - * - * @param cb The action to perform for each measure - */ - function forEachMeasure(cb) { - measures.forEach(function (measure, key) { - cb(key, measure); - }); - } - performance.forEachMeasure = forEachMeasure; - /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - counts = ts.createMap(); - marks = ts.createMap(); - measures = ts.createMap(); - enabled = true; - profilerStart = ts.timestamp(); - } - performance.enable = enable; - /** Disables performance measurements for the compiler. */ - function disable() { - enabled = false; - } - performance.disable = disable; - })(performance = ts.performance || (ts.performance = {})); -})(ts || (ts = {})); + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + } + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.0"; + ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); -/* @internal */ (function (ts) { + /* @internal */ var Comparison; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -935,23 +915,6 @@ var ts; return array.slice().sort(comparer); } ts.sort = sort; - function best(iter, isBetter) { - var x = iter.next(); - if (x.done) { - return undefined; - } - var best = x.value; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) { - return best; - } - if (isBetter(value, best)) { - best = value; - } - } - } - ts.best = best; function arrayIterator(array) { var i = 0; return { next: function () { @@ -1721,6 +1684,9 @@ var ts; if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { var candidateNameLowerCase = candidateName.toLowerCase(); if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } return candidate; } if (justCheckExactMatches) { @@ -1912,8 +1878,9 @@ var ts; return startsWith(str, prefix) ? str.substr(prefix.length) : str; } ts.removePrefix = removePrefix; - function tryRemovePrefix(str, prefix) { - return startsWith(str, prefix) ? str.substring(prefix.length) : undefined; + function tryRemovePrefix(str, prefix, getCanonicalFileName) { + if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; } + return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; } ts.tryRemovePrefix = tryRemovePrefix; function isPatternMatch(_a, candidate) { @@ -1930,8 +1897,8 @@ var ts; return function (arg) { return f(arg) || g(arg); }; } ts.or = or; - function assertTypeIsNever(_) { } // tslint:disable-line no-empty - ts.assertTypeIsNever = assertTypeIsNever; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -1969,16 +1936,99 @@ var ts; } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; })(ts || (ts = {})); -//# sourceMappingURL=core.js.map -"use strict"; -var __assign = (this && this.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; -}; +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +(function (ts) { + var performance; + (function (performance) { + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks.set(markName, ts.timestamp()); + counts.set(markName, (counts.get(markName) || 0) + 1); + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); + var start = startMarkName && marks.get(startMarkName) || profilerStart; + measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts.get(markName) || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures.get(measureName) || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + measures.forEach(function (measure, key) { + cb(key, measure); + }); + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2170,159 +2220,164 @@ var ts; SyntaxKind[SyntaxKind["TypeLiteral"] = 166] = "TypeLiteral"; SyntaxKind[SyntaxKind["ArrayType"] = 167] = "ArrayType"; SyntaxKind[SyntaxKind["TupleType"] = 168] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 169] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 170] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 171] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 172] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 173] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 174] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 175] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 176] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 177] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 178] = "LiteralType"; - SyntaxKind[SyntaxKind["ImportType"] = 179] = "ImportType"; + SyntaxKind[SyntaxKind["OptionalType"] = 169] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 170] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 171] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 172] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 173] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 174] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 175] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 176] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 177] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 178] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 179] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 180] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 181] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 180] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 181] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 182] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 182] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 183] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 184] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 183] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 184] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 185] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 186] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 187] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 188] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 189] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 190] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 191] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 192] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 193] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 194] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 195] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 196] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 197] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 198] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 199] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 200] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 201] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 202] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 203] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 204] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 205] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 206] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 207] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 208] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 209] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 210] = "MetaProperty"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 185] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 186] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 187] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 188] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 189] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 190] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 191] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 192] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 193] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 194] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 195] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 196] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 197] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 198] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 199] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 200] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 201] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 202] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 203] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 204] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 205] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 206] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 207] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 208] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 209] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 210] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 211] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 212] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 213] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 211] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 212] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 214] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 215] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 213] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 214] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 215] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 216] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 217] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 218] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 219] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 220] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 221] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 222] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 223] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 224] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 225] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 226] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 227] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 228] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 229] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 230] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 231] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 232] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 233] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 234] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 235] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 236] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 237] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 238] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 239] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 240] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 241] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 242] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 243] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 244] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 245] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 246] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 247] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 248] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 249] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 250] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 251] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 252] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 253] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 216] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 217] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 218] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 219] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 220] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 221] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 222] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 223] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 224] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 225] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 226] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 227] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 228] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 229] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 230] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 231] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 232] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 233] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 234] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 235] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 236] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 237] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 238] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 239] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 240] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 241] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 242] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 243] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 244] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 245] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 246] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 247] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 248] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 249] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 250] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 251] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 252] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 253] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 254] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 255] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 256] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 254] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 257] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 255] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 256] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 257] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 258] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 259] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 260] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 261] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 262] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 263] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 264] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 265] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 258] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 259] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 260] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 261] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 262] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 263] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 264] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 265] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 266] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 267] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 268] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 266] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 267] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 268] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 269] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 269] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 270] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 271] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 272] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 270] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 271] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 272] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 273] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 274] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 275] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 273] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 276] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 274] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 275] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 276] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 277] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 277] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 278] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 279] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 280] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 278] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 281] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 279] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 282] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 280] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 281] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 282] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 283] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 284] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 285] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 286] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 287] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 288] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 289] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 290] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 291] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 292] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 293] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 294] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 295] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 296] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 297] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 298] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 283] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 284] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 285] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 286] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 287] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 288] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 289] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 290] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 291] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 292] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 299] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 300] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 301] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 302] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 303] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 304] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 305] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -2335,7 +2390,7 @@ var ts; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; SyntaxKind[SyntaxKind["FirstTypeNode"] = 161] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 179] = "LastTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 181] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; @@ -2349,10 +2404,10 @@ var ts; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 278] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 298] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 289] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 298] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -2526,6 +2581,7 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; @@ -2679,6 +2735,7 @@ var ts; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; @@ -2712,8 +2769,6 @@ var ts; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasExports"] = 1955] = "HasExports"; - SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; @@ -2745,6 +2800,8 @@ var ts; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Late"] = 1024] = "Late"; CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -2765,6 +2822,7 @@ var ts; InternalSymbolName["Resolving"] = "__resolving__"; InternalSymbolName["ExportEquals"] = "export="; InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); /* @internal */ var NodeCheckFlags; @@ -2821,7 +2879,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["UnionOfUnitTypes"] = 67108864] = "UnionOfUnitTypes"; + TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2864,7 +2922,7 @@ var ts; TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotUnit"] = 16749629] = "NotUnit"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2898,6 +2956,7 @@ var ts; ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -3755,52 +3814,80 @@ var ts; */ /*@internal*/ function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); return createDirectoryWatcher; /** * Create the directory watcher for the dirPath. */ function createDirectoryWatcher(dirName, callback) { - var watcher = host.watchDirectory(dirName, function (fileName) { - // Call the actual callback - callback(fileName); - // Iterate through existing children and update the watches if needed - updateChildWatches(result, callback); - }); - var result = { - close: function () { - watcher.close(); - result.childWatches.forEach(ts.closeFileWatcher); - result = undefined; - }, + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { dirName: dirName, - childWatches: ts.emptyArray + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } }; - updateChildWatches(result, callback); - return result; } - function updateChildWatches(watcher, callback) { + function updateChildWatches(dirName, dirPath) { // Iterate through existing children and update the watches if needed - if (watcher) { - watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); } } /** * Watch the directories in the parentDir */ - function watchChildDirectories(parentDir, existingChildWatches, callback) { + function watchChildDirectories(parentDir, existingChildWatches) { var newChildWatches; ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch - return host.filePathComparer(childFullName, host.realpath(childFullName)) === 0 /* EqualTo */ ? childFullName : undefined; - }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); return newChildWatches || ts.emptyArray; /** * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName) { - var result = createDirectoryWatcher(childName, callback); + var result = createDirectoryWatcher(childName); addChildDirectoryWatcher(result); } /** @@ -3827,7 +3914,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; - // TODO: this is used as if it's certainly defined in many places. + // TODO: GH#18217 this is used as if it's certainly defined in many places. ts.sys = (function () { // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual // byte order mark from the specified encoding. Using any other byte order mark does @@ -3936,18 +4023,17 @@ var ts; process.stdout._handle.setBlocking(true); } }, - base64decode: Buffer.from ? function (input) { - return Buffer.from(input, "base64").toString("utf8"); - } : function (input) { - return new Buffer(input, "base64").toString("utf8"); - }, - base64encode: Buffer.from ? function (input) { - return Buffer.from(input).toString("base64"); - } : function (input) { - return new Buffer(input).toString("base64"); - } + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, }; return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } function isFileSystemCaseSensitive() { // win32\win64 are case insensitive platforms if (platform === "win32" || platform === "win64") { @@ -4000,7 +4086,7 @@ var ts; createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : watchDirectoryUsingFsWatch; var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ - filePathComparer: ts.getStringComparer(!useCaseSensitiveFileNames), + useCaseSensitiveFileNames: useCaseSensitiveFileNames, directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, watchDirectory: watchDirectory, @@ -4010,8 +4096,7 @@ var ts; if (recursive) { return watchDirectoryRecursively(directoryName, callback); } - watchDirectory(directoryName, callback); - return undefined; // TODO: GH#18217 + return watchDirectory(directoryName, callback); }; } function createNonPollingWatchFile() { @@ -4255,8 +4340,8 @@ var ts; var entries = _fs.readdirSync(path || ".").sort(); var files = []; var directories = []; - for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { - var entry = entries_1[_i]; + for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { + var entry = entries_2[_i]; // This is necessary because on some file system node fails to exclude // "." and "..". See https://github.com/nodejs/node/issues/4002 if (entry === "." || entry === "..") { @@ -4379,6 +4464,9 @@ var ts; }, resolvePath: ChakraHost.resolvePath, fileExists: ChakraHost.fileExists, + deleteFile: ChakraHost.deleteFile, + getModifiedTime: ChakraHost.getModifiedTime, + setModifiedTime: ChakraHost.setModifiedTime, directoryExists: ChakraHost.directoryExists, createDirectory: ChakraHost.createDirectory, getExecutingFilePath: function () { return ChakraHost.executingFile; }, @@ -4436,7 +4524,7 @@ var ts; } })(ts || (ts = {})); // -// generated from './diagnosticInformationMap.generated.ts' by 'src\parser' +// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ var ts; (function (ts) { @@ -4537,7 +4625,6 @@ var ts; An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), - A_tuple_type_element_list_cannot_be_empty: diag(1122, ts.DiagnosticCategory.Error, "A_tuple_type_element_list_cannot_be_empty_1122", "A tuple type element list cannot be empty."), Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), @@ -4657,6 +4744,8 @@ var ts; _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), + A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), @@ -4687,9 +4776,11 @@ var ts; An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), - Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340", "Module '{0}' does not refer to a type, but is used as a type here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4742,7 +4833,7 @@ var ts; Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), - Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), @@ -4757,6 +4848,7 @@ var ts; The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), @@ -4806,6 +4898,7 @@ var ts; Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), @@ -4953,6 +5046,12 @@ var ts; Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"), Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), + Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), + A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), 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."), @@ -5039,6 +5138,11 @@ var ts; Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), 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}'."), @@ -5152,6 +5256,7 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5338,6 +5443,11 @@ var ts; Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5369,6 +5479,8 @@ var ts; Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5395,11 +5507,14 @@ var ts; Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), - A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5429,6 +5544,7 @@ var ts; Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), 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."), @@ -5459,6 +5575,7 @@ var ts; Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), @@ -5469,6 +5586,8 @@ var ts; Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5486,6 +5605,10 @@ var ts; Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), 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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5544,6 +5667,12 @@ var ts; Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), }; })(ts || (ts = {})); var ts; @@ -7297,6 +7426,7 @@ var ts; } function scanJSDocToken() { startPos = tokenPos = pos; + tokenFlags = 0; if (pos >= end) { return token = 1 /* EndOfFileToken */; } @@ -7315,6 +7445,7 @@ var ts; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: return token = 39 /* AsteriskToken */; @@ -7430,11 +7561,6 @@ var ts; /** Non-internal stuff goes here */ var ts; (function (ts) { - ts.emptyArray = []; - function closeFileWatcher(watcher) { - watcher.close(); - } - ts.closeFileWatcher = closeFileWatcher; function isExternalModuleNameRelative(moduleName) { // TypeScript 1.0 spec (April 2014): 11.2.1 // An external module name is "relative" if the first term is "." or "..". @@ -7446,24 +7572,15 @@ var ts; return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); } ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; - function hasEntries(map) { - return !!map && !!map.size; - } - ts.hasEntries = hasEntries; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -7482,6 +7599,10 @@ var ts; return new ts.MapCtr(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function hasEntries(map) { + return !!map && !!map.size; + } + ts.hasEntries = hasEntries; function createSymbolTable(symbols) { var result = ts.createMap(); if (symbols) { @@ -7528,6 +7649,13 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) + ? ts.normalizePath(fileName) + : ts.getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return !oldOptions || (oldOptions.module !== newOptions.module) || @@ -7561,6 +7689,19 @@ var ts; return undefined; } ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; function forEachEntry(map, callback) { var _a; var iterator = map.entries(); @@ -7696,7 +7837,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 274 /* SourceFile */) { + while (node && node.kind !== 277 /* SourceFile */) { node = node.parent; } return node; @@ -7704,11 +7845,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 213 /* Block */: - case 241 /* CaseBlock */: - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: + case 216 /* Block */: + case 244 /* CaseBlock */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: return true; } return false; @@ -7784,26 +7925,22 @@ var ts; } ts.nodeIsPresent = nodeIsPresent; /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. + * Prepends statements to an array while taking care of prologue directives. */ - function prependStatements(to, from) { + function addStatementsAfterPrologue(to, from) { if (from === undefined || from.length === 0) return to; - if (to === undefined) - return from.slice(); - var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); - to.unshift.apply(to, from); - if (prologue) { - to.unshift(prologue); + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } } + to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.prependStatements = prependStatements; + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; /** * Determine if the given comment is a triple-slash * @@ -7846,7 +7983,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 299 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -7934,19 +8071,6 @@ var ts; return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; - // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' - function escapeLeadingUnderscores(identifier) { - return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); - } - ts.escapeLeadingUnderscores = escapeLeadingUnderscores; - /** - * @deprecated Use `id.escapedText` to get the escaped text of an Identifier. - * @param identifier The identifier to escape - */ - function escapeIdentifier(identifier) { - return identifier; - } - ts.escapeIdentifier = escapeIdentifier; // Make an identifier from an external module name by extracting the string after the last "/" and replacing // all non-alphanumeric characters with underscores function makeIdentifierFromModuleName(moduleName) { @@ -7960,7 +8084,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 232 /* VariableDeclaration */ && node.parent.kind === 269 /* CatchClause */; + return node.kind === 235 /* VariableDeclaration */ && node.parent.kind === 272 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -7992,11 +8116,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 239 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 242 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 274 /* SourceFile */ || - node.kind === 239 /* ModuleDeclaration */ || + return node.kind === 277 /* SourceFile */ || + node.kind === 242 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -8013,36 +8137,40 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 274 /* SourceFile */: + case 277 /* SourceFile */: return ts.isExternalModule(node.parent); - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 274 /* SourceFile */: - case 241 /* CaseBlock */: - case 269 /* CatchClause */: - case 239 /* ModuleDeclaration */: - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: + case 277 /* SourceFile */: + case 244 /* CaseBlock */: + case 272 /* CatchClause */: + case 242 /* ModuleDeclaration */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: case 155 /* Constructor */: case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; - case 213 /* Block */: + case 216 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -8051,6 +8179,18 @@ var ts; } ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 291 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { case 158 /* CallSignature */: case 159 /* ConstructSignature */: @@ -8058,33 +8198,30 @@ var ts; case 160 /* IndexSignature */: case 163 /* FunctionType */: case 164 /* ConstructorType */: - case 284 /* JSDocFunctionType */: - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 296 /* JSDocTemplateTag */: - case 234 /* FunctionDeclaration */: + case 287 /* JSDocFunctionType */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 301 /* JSDocTemplateTag */: + case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: - case 292 /* JSDocCallbackTag */: - case 297 /* JSDocTypedefTag */: - case 288 /* JSDocSignature */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; default: - ts.assertTypeIsNever(node); + ts.assertType(node); return false; } } - ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: - case 243 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: return true; default: return false; @@ -8093,15 +8230,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: - case 243 /* ImportEqualsDeclaration */: - case 214 /* VariableStatement */: - case 235 /* ClassDeclaration */: - case 234 /* FunctionDeclaration */: - case 239 /* ModuleDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 236 /* InterfaceDeclaration */: - case 238 /* EnumDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 217 /* VariableStatement */: + case 238 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: return true; default: return false; @@ -8122,7 +8259,7 @@ var ts; // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. function declarationNameToString(name) { - return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } ts.declarationNameToString = declarationNameToString; function getNameFromIndexInfo(info) { @@ -8135,11 +8272,11 @@ var ts; return name.escapedText; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return escapeLeadingUnderscores(name.text); + return ts.escapeLeadingUnderscores(name.text); case 147 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } ts.getTextOfPropertyName = getTextOfPropertyName; @@ -8149,7 +8286,7 @@ var ts; return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); case 146 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); default: throw ts.Debug.assertNever(name); @@ -8171,7 +8308,7 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeFromMessageChain(node, messageChain) { + function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); return { @@ -8180,7 +8317,8 @@ var ts; length: span.length, code: messageChain.code, category: messageChain.category, - messageText: messageChain.next ? messageChain : messageChain.messageText + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation: relatedInformation }; } ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; @@ -8193,7 +8331,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 213 /* Block */) { + if (node.body && node.body.kind === 216 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -8207,7 +8345,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 274 /* SourceFile */: + case 277 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -8216,25 +8354,25 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 232 /* VariableDeclaration */: - case 182 /* BindingElement */: - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 236 /* InterfaceDeclaration */: - case 239 /* ModuleDeclaration */: - case 238 /* EnumDeclaration */: - case 273 /* EnumMember */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: errorNode = node.name; break; - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -8266,35 +8404,32 @@ var ts; return file.scriptKind === 6 /* JSON */; } ts.isJsonSourceFile = isJsonSourceFile; - function isConstEnumDeclaration(node) { - return node.kind === 238 /* EnumDeclaration */ && isConst(node); + function isEnumConst(node) { + return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } - ts.isConstEnumDeclaration = isConstEnumDeclaration; - function isConst(node) { - return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */) - || !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); + ts.isEnumConst = isEnumConst; + function isVarConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } - ts.isConst = isConst; + ts.isVarConst = isVarConst; function isLet(node) { return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 187 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 189 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 187 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 189 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { - return n.kind === 179 /* ImportType */ && - n.argument.kind === 178 /* LiteralType */ && - ts.isStringLiteral(n.argument.literal); + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 216 /* ExpressionStatement */ + return node.kind === 219 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -8305,9 +8440,9 @@ var ts; function getJSDocCommentRanges(node, text) { var commentRanges = (node.kind === 149 /* Parameter */ || node.kind === 148 /* TypeParameter */ || - node.kind === 192 /* FunctionExpression */ || - node.kind === 193 /* ArrowFunction */ || - node.kind === 191 /* ParenthesizedExpression */) ? + node.kind === 194 /* FunctionExpression */ || + node.kind === 195 /* ArrowFunction */ || + node.kind === 193 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -8323,7 +8458,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 179 /* LastTypeNode */) { + if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 181 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -8337,11 +8472,11 @@ var ts; case 131 /* NeverKeyword */: return true; case 105 /* VoidKeyword */: - return node.parent.kind !== 196 /* VoidExpression */; - case 207 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 198 /* VoidExpression */; + case 209 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); case 148 /* TypeParameter */: - return node.parent.kind === 177 /* MappedType */ || node.parent.kind === 172 /* InferType */; + return node.parent.kind === 179 /* MappedType */ || node.parent.kind === 174 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 71 /* Identifier */: @@ -8349,20 +8484,20 @@ var ts; if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 185 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 185 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 187 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through case 146 /* QualifiedName */: - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: case 99 /* ThisKeyword */: { var parent = node.parent; if (parent.kind === 165 /* TypeQuery */) { return false; } - if (parent.kind === 179 /* ImportType */) { + if (parent.kind === 181 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -8371,22 +8506,24 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 179 /* LastTypeNode */) { + if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 181 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case 148 /* TypeParameter */: return node === parent.constraint; + case 301 /* JSDocTemplateTag */: + return node === parent.constraint; case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: case 149 /* Parameter */: - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return node === parent.type; - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: case 155 /* Constructor */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: @@ -8397,12 +8534,12 @@ var ts; case 159 /* ConstructSignature */: case 160 /* IndexSignature */: return node === parent.type; - case 190 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: return node === parent.type; - case 187 /* CallExpression */: - case 188 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -8427,23 +8564,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitor(node); - case 241 /* CaseBlock */: - case 213 /* Block */: - case 217 /* IfStatement */: - case 218 /* DoStatement */: - case 219 /* WhileStatement */: - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 226 /* WithStatement */: - case 227 /* SwitchStatement */: - case 266 /* CaseClause */: - case 267 /* DefaultClause */: - case 228 /* LabeledStatement */: - case 230 /* TryStatement */: - case 269 /* CatchClause */: + case 244 /* CaseBlock */: + case 216 /* Block */: + case 220 /* IfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 229 /* WithStatement */: + case 230 /* SwitchStatement */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + case 231 /* LabeledStatement */: + case 233 /* TryStatement */: + case 272 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -8453,19 +8590,19 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 238 /* EnumDeclaration */: - case 236 /* InterfaceDeclaration */: - case 239 /* ModuleDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 241 /* EnumDeclaration */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -8508,12 +8645,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 236 /* InterfaceDeclaration */: - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: case 166 /* TypeLiteral */: return node.members; - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return node.properties; } } @@ -8521,14 +8658,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 182 /* BindingElement */: - case 273 /* EnumMember */: + case 184 /* BindingElement */: + case 276 /* EnumMember */: case 149 /* Parameter */: - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: - case 271 /* ShorthandPropertyAssignment */: - case 232 /* VariableDeclaration */: + case 274 /* ShorthandPropertyAssignment */: + case 235 /* VariableDeclaration */: return true; } } @@ -8540,12 +8677,12 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 233 /* VariableDeclarationList */ - && node.parent.parent.kind === 214 /* VariableStatement */; + return node.parent.kind === 236 /* VariableDeclarationList */ + && node.parent.parent.kind === 217 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { - return ts.isVariableDeclaration(node) ? isConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : ts.isPropertySignature(node) && hasReadonlyModifier(node); } @@ -8557,8 +8694,8 @@ var ts; case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return true; } return false; @@ -8569,7 +8706,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 228 /* LabeledStatement */) { + if (node.statement.kind !== 231 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -8577,17 +8714,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 213 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 216 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 184 /* ObjectLiteralExpression */; + return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 186 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { return node.kind === 154 /* MethodDeclaration */ && - (node.parent.kind === 184 /* ObjectLiteralExpression */ || - node.parent.kind === 205 /* ClassExpression */); + (node.parent.kind === 186 /* ObjectLiteralExpression */ || + node.parent.kind === 207 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -8600,7 +8737,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 270 /* PropertyAssignment */) { + if (property.kind === 273 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -8637,7 +8774,7 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 274 /* SourceFile */); + ts.Debug.assert(node.kind !== 277 /* SourceFile */); while (true) { node = node.parent; if (!node) { @@ -8672,14 +8809,14 @@ var ts; node = node.parent; } break; - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 239 /* ModuleDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 242 /* ModuleDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: case 154 /* MethodDeclaration */: @@ -8690,8 +8827,8 @@ var ts; case 158 /* CallSignature */: case 159 /* ConstructSignature */: case 160 /* IndexSignature */: - case 238 /* EnumDeclaration */: - case 274 /* SourceFile */: + case 241 /* EnumDeclaration */: + case 277 /* SourceFile */: return node; } } @@ -8702,8 +8839,8 @@ var ts; if (container) { switch (container.kind) { case 155 /* Constructor */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return container; } } @@ -8728,9 +8865,9 @@ var ts; case 147 /* ComputedPropertyName */: node = node.parent; break; - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: if (!stopOnFunctions) { continue; } @@ -8761,14 +8898,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 192 /* FunctionExpression */ || func.kind === 193 /* ArrowFunction */) { + if (func.kind === 194 /* FunctionExpression */ || func.kind === 195 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 191 /* ParenthesizedExpression */) { + while (parent.kind === 193 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 187 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 189 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -8779,7 +8916,7 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 185 /* PropertyAccessExpression */ || kind === 186 /* ElementAccessExpression */) + return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) && node.expression.kind === 97 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; @@ -8788,7 +8925,7 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 185 /* PropertyAccessExpression */ || kind === 186 /* ElementAccessExpression */) + return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) && node.expression.kind === 99 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; @@ -8796,7 +8933,7 @@ var ts; switch (node.kind) { case 162 /* TypeReference */: return node.typeName; - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; @@ -8809,10 +8946,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return node.tag; - case 257 /* JsxOpeningElement */: - case 256 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -8821,25 +8958,25 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: // classes are valid targets return true; case 152 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 235 /* ClassDeclaration */; + return parent.kind === 238 /* ClassDeclaration */; case 156 /* GetAccessor */: case 157 /* SetAccessor */: case 154 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 235 /* ClassDeclaration */; + && parent.kind === 238 /* ClassDeclaration */; case 149 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined && (parent.kind === 155 /* Constructor */ || parent.kind === 154 /* MethodDeclaration */ || parent.kind === 157 /* SetAccessor */) - && grandparent.kind === 235 /* ClassDeclaration */; + && grandparent.kind === 238 /* ClassDeclaration */; } return false; } @@ -8855,7 +8992,7 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 case 154 /* MethodDeclaration */: case 157 /* SetAccessor */: @@ -8867,9 +9004,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 257 /* JsxOpeningElement */ || - parent.kind === 256 /* JsxSelfClosingElement */ || - parent.kind === 258 /* JsxClosingElement */) { + if (parent.kind === 260 /* JsxOpeningElement */ || + parent.kind === 259 /* JsxSelfClosingElement */ || + parent.kind === 261 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -8882,37 +9019,37 @@ var ts; case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 12 /* RegularExpressionLiteral */: - case 183 /* ArrayLiteralExpression */: - case 184 /* ObjectLiteralExpression */: - case 185 /* PropertyAccessExpression */: - case 186 /* ElementAccessExpression */: - case 187 /* CallExpression */: - case 188 /* NewExpression */: - case 189 /* TaggedTemplateExpression */: - case 208 /* AsExpression */: - case 190 /* TypeAssertionExpression */: - case 209 /* NonNullExpression */: - case 191 /* ParenthesizedExpression */: - case 192 /* FunctionExpression */: - case 205 /* ClassExpression */: - case 193 /* ArrowFunction */: - case 196 /* VoidExpression */: - case 194 /* DeleteExpression */: - case 195 /* TypeOfExpression */: - case 198 /* PrefixUnaryExpression */: - case 199 /* PostfixUnaryExpression */: - case 200 /* BinaryExpression */: - case 201 /* ConditionalExpression */: - case 204 /* SpreadElement */: - case 202 /* TemplateExpression */: + case 185 /* ArrayLiteralExpression */: + case 186 /* ObjectLiteralExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 191 /* TaggedTemplateExpression */: + case 210 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 211 /* NonNullExpression */: + case 193 /* ParenthesizedExpression */: + case 194 /* FunctionExpression */: + case 207 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 198 /* VoidExpression */: + case 196 /* DeleteExpression */: + case 197 /* TypeOfExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 202 /* BinaryExpression */: + case 203 /* ConditionalExpression */: + case 206 /* SpreadElement */: + case 204 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: - case 206 /* OmittedExpression */: - case 255 /* JsxElement */: - case 256 /* JsxSelfClosingElement */: - case 259 /* JsxFragment */: - case 203 /* YieldExpression */: - case 197 /* AwaitExpression */: - case 210 /* MetaProperty */: + case 208 /* OmittedExpression */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 262 /* JsxFragment */: + case 205 /* YieldExpression */: + case 199 /* AwaitExpression */: + case 212 /* MetaProperty */: return true; case 146 /* QualifiedName */: while (node.parent.kind === 146 /* QualifiedName */) { @@ -8936,55 +9073,57 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: case 149 /* Parameter */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: - case 273 /* EnumMember */: - case 270 /* PropertyAssignment */: - case 182 /* BindingElement */: + case 276 /* EnumMember */: + case 273 /* PropertyAssignment */: + case 184 /* BindingElement */: return parent.initializer === node; - case 216 /* ExpressionStatement */: - case 217 /* IfStatement */: - case 218 /* DoStatement */: - case 219 /* WhileStatement */: - case 225 /* ReturnStatement */: - case 226 /* WithStatement */: - case 227 /* SwitchStatement */: - case 266 /* CaseClause */: - case 229 /* ThrowStatement */: + case 219 /* ExpressionStatement */: + case 220 /* IfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 228 /* ReturnStatement */: + case 229 /* WithStatement */: + case 230 /* SwitchStatement */: + case 269 /* CaseClause */: + case 232 /* ThrowStatement */: return parent.expression === node; - case 220 /* ForStatement */: + case 223 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 233 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 236 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 233 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236 /* VariableDeclarationList */) || forInStatement.expression === node; - case 190 /* TypeAssertionExpression */: - case 208 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: return node === parent.expression; - case 211 /* TemplateSpan */: + case 214 /* TemplateSpan */: return node === parent.expression; case 147 /* ComputedPropertyName */: return node === parent.expression; case 150 /* Decorator */: - case 265 /* JsxExpression */: - case 264 /* JsxSpreadAttribute */: - case 272 /* SpreadAssignment */: + case 268 /* JsxExpression */: + case 267 /* JsxSpreadAttribute */: + case 275 /* SpreadAssignment */: return true; - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 274 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); } } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 243 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 254 /* ExternalModuleReference */; + return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -8993,7 +9132,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 243 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 254 /* ExternalModuleReference */; + return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -9025,7 +9164,7 @@ var ts; } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { - if (callExpression.kind !== 187 /* CallExpression */) { + if (callExpression.kind !== 189 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -9048,12 +9187,15 @@ var ts; } ts.isStringDoubleQuoted = isStringDoubleQuoted; function getDeclarationOfJSInitializer(node) { - if (!isInJavaScriptFile(node) || !node.parent) { + if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + return undefined; + } name = node.parent.name; decl = node.parent; } @@ -9090,6 +9232,12 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; + /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ + function getDeclaredJavascriptInitializer(node) { + var init = getEffectiveInitializer(node); + return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + } + ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; /** * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. @@ -9115,11 +9263,11 @@ var ts; function getJavascriptInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 192 /* FunctionExpression */ || e.kind === 193 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 192 /* FunctionExpression */ || - initializer.kind === 205 /* ClassExpression */ || - initializer.kind === 193 /* ArrowFunction */) { + if (initializer.kind === 194 /* FunctionExpression */ || + initializer.kind === 207 /* ClassExpression */ || + initializer.kind === 195 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -9188,7 +9336,7 @@ var ts; return false; } function getRightMostAssignedExpression(node) { - while (isAssignmentExpression(node, /*excludeCompoundAssignements*/ true)) { + while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) { node = node.right; } return node; @@ -9205,12 +9353,23 @@ var ts; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder function getSpecialPropertyAssignmentKind(expr) { - if (!isInJavaScriptFile(expr) || - expr.operatorToken.kind !== 58 /* EqualsToken */ || + var special = getSpecialPropertyAssignmentKindWorker(expr); + return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getSpecialPropertyAssignmentKindWorker(expr) { + if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } var lhs = expr.left; + if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + // F.prototype = { ... } + return 6 /* Prototype */; + } + return getSpecialPropertyAccessKind(lhs); + } + function getSpecialPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9219,11 +9378,7 @@ var ts; return 2 /* ModuleExports */; } else if (isEntityNameExpression(lhs.expression)) { - if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { - // F.prototype = { ... } - return 6 /* Prototype */; - } - else if (isPrototypeAccess(lhs.expression)) { + if (isPrototypeAccess(lhs.expression)) { // F.G....prototype.x = expr return 3 /* PrototypeProperty */; } @@ -9243,7 +9398,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9257,24 +9412,32 @@ var ts; ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJavaScriptFile(expr) && - expr.parent && expr.parent.kind === 216 /* ExpressionStatement */ && + expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); } ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 244 /* ImportDeclaration */: - case 250 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: return node.parent; - case 254 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: return node.parent.parent; - case 187 /* CallExpression */: + case 189 /* CallExpression */: return node.parent; - case 178 /* LiteralType */: + case 180 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -9284,12 +9447,12 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: - case 250 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: return node.moduleSpecifier; - case 243 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 254 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 179 /* ImportType */: + case 246 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 257 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 181 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; default: return ts.Debug.assertNever(node); @@ -9298,11 +9461,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return node; - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return undefined; default: return ts.Debug.assertNever(node); @@ -9310,7 +9473,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 244 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 247 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { @@ -9319,8 +9482,8 @@ var ts; case 149 /* Parameter */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: - case 271 /* ShorthandPropertyAssignment */: - case 270 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: return node.questionToken !== undefined; @@ -9330,14 +9493,14 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 284 /* JSDocFunctionType */ && + return node.kind === 287 /* JSDocFunctionType */ && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 297 /* JSDocTypedefTag */ || node.kind === 292 /* JSDocCallbackTag */; + return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9362,12 +9525,12 @@ var ts; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; case 152 /* PropertyDeclaration */: return node.initializer; - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return node.initializer; } } @@ -9377,54 +9540,57 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 239 /* ModuleDeclaration */ + node.body.kind === 242 /* ModuleDeclaration */ ? node.body : undefined; } function getJSDocCommentsAndTags(hostNode) { var result; - getJSDocCommentsAndTagsWorker(hostNode); - return result || ts.emptyArray; - function getJSDocCommentsAndTagsWorker(node) { - var parent = node.parent; - if (!parent) - return; - if (parent.kind === 270 /* PropertyAssignment */ || parent.kind === 152 /* PropertyDeclaration */ || getNestedModuleDeclaration(parent)) { - getJSDocCommentsAndTagsWorker(parent); - } - // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. - // /** - // * @param {number} name - // * @returns {number} - // */ - // var x = function(name) { return name.length; } - if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) { - getJSDocCommentsAndTagsWorker(parent.parent); - } - if (parent.parent && parent.parent.parent && - (getSingleVariableOfVariableStatement(parent.parent.parent) || - getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || - getSourceOfDefaultedAssignment(parent.parent.parent))) { - getJSDocCommentsAndTagsWorker(parent.parent.parent); - } - if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */ || - ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */ || - node.kind === 185 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 216 /* ExpressionStatement */) { - getJSDocCommentsAndTagsWorker(parent); - } - // Pull parameter comments from declaring function as well - if (node.kind === 149 /* Parameter */) { - result = ts.addRange(result, ts.getJSDocParameterTags(node)); - } - if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) { - result = ts.addRange(result, node.initializer.jsDoc); - } + // Pull parameter comments from declaring function as well + if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) { + result = ts.addRange(result, hostNode.initializer.jsDoc); + } + var node = hostNode; + while (node && node.parent) { if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, node.jsDoc); } + if (node.kind === 149 /* Parameter */) { + result = ts.addRange(result, ts.getJSDocParameterTags(node)); + break; + } + node = getNextJSDocCommentLocation(node); } + return result || ts.emptyArray; } ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + function getNextJSDocCommentLocation(node) { + var parent = node.parent; + if (parent.kind === 273 /* PropertyAssignment */ || + parent.kind === 152 /* PropertyDeclaration */ || + parent.kind === 219 /* ExpressionStatement */ && node.kind === 187 /* PropertyAccessExpression */ || + getNestedModuleDeclaration(parent) || + ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */) { + return parent; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + else if (parent.parent && + (getSingleVariableOfVariableStatement(parent.parent) === node || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */)) { + return parent.parent; + } + else if (parent.parent && parent.parent.parent && + (getSingleVariableOfVariableStatement(parent.parent.parent) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } + } /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ function getParameterSymbolFromJSDoc(node) { if (node.symbol) { @@ -9473,7 +9639,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 285 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 288 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9486,31 +9652,31 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 198 /* PrefixUnaryExpression */: - case 199 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 191 /* ParenthesizedExpression */: - case 183 /* ArrayLiteralExpression */: - case 204 /* SpreadElement */: - case 209 /* NonNullExpression */: + case 193 /* ParenthesizedExpression */: + case 185 /* ArrayLiteralExpression */: + case 206 /* SpreadElement */: + case 211 /* NonNullExpression */: node = parent; break; - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -9537,22 +9703,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 213 /* Block */: - case 214 /* VariableStatement */: - case 226 /* WithStatement */: - case 217 /* IfStatement */: - case 227 /* SwitchStatement */: - case 241 /* CaseBlock */: - case 266 /* CaseClause */: - case 267 /* DefaultClause */: - case 228 /* LabeledStatement */: - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 218 /* DoStatement */: - case 219 /* WhileStatement */: - case 230 /* TryStatement */: - case 269 /* CatchClause */: + case 216 /* Block */: + case 217 /* VariableStatement */: + case 229 /* WithStatement */: + case 220 /* IfStatement */: + case 230 /* SwitchStatement */: + case 244 /* CaseBlock */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + case 231 /* LabeledStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 233 /* TryStatement */: + case 272 /* CatchClause */: return true; } return false; @@ -9569,15 +9735,15 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 173 /* ParenthesizedType */); + return walkUp(node, 175 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 191 /* ParenthesizedExpression */); + return walkUp(node, 193 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 191 /* ParenthesizedExpression */) { + while (node.kind === 193 /* ParenthesizedExpression */) { node = node.expression; } return node; @@ -9585,11 +9751,11 @@ var ts; ts.skipParentheses = skipParentheses; // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 185 /* PropertyAccessExpression */ && node.kind !== 186 /* ElementAccessExpression */) { + if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 194 /* DeleteExpression */; + return node && node.kind === 196 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -9622,7 +9788,10 @@ var ts; } else { var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + return ts.isBinaryExpression(binExp) && + getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name; } } default: @@ -9646,9 +9815,9 @@ var ts; case 153 /* MethodSignature */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 273 /* EnumMember */: - case 270 /* PropertyAssignment */: - case 185 /* PropertyAccessExpression */: + case 276 /* EnumMember */: + case 273 /* PropertyAssignment */: + case 187 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; case 146 /* QualifiedName */: @@ -9660,12 +9829,12 @@ var ts; return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */; } return false; - case 182 /* BindingElement */: - case 248 /* ImportSpecifier */: + case 184 /* BindingElement */: + case 251 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 252 /* ExportSpecifier */: - case 262 /* JsxAttribute */: + case 255 /* ExportSpecifier */: + case 265 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -9681,13 +9850,13 @@ var ts; // export = // export default function isAliasSymbolDeclaration(node) { - return node.kind === 243 /* ImportEqualsDeclaration */ || - node.kind === 242 /* NamespaceExportDeclaration */ || - node.kind === 245 /* ImportClause */ && !!node.name || - node.kind === 246 /* NamespaceImport */ || - node.kind === 248 /* ImportSpecifier */ || - node.kind === 252 /* ExportSpecifier */ || - node.kind === 249 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + return node.kind === 246 /* ImportEqualsDeclaration */ || + node.kind === 245 /* NamespaceExportDeclaration */ || + node.kind === 248 /* ImportClause */ && !!node.name || + node.kind === 249 /* NamespaceImport */ || + node.kind === 251 /* ImportSpecifier */ || + node.kind === 255 /* ExportSpecifier */ || + node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; @@ -9696,11 +9865,22 @@ var ts; return isEntityNameExpression(e) || ts.isClassExpression(e); } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; - function getClassExtendsHeritageClauseElement(node) { + function getEffectiveBaseTypeNode(node) { + if (isInJavaScriptFile(node)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return getClassExtendsHeritageElement(node); + } + ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; + function getClassExtendsHeritageElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } - ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; + ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; function getClassImplementsHeritageClauseElements(node) { var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; @@ -9709,7 +9889,7 @@ var ts; /** Returns the node in an `extends` or `implements` clause of a class or interface. */ function getAllSuperTypeNodes(node) { return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray - : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getClassExtendsHeritageClauseElement(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray : ts.emptyArray; } ts.getAllSuperTypeNodes = getAllSuperTypeNodes; @@ -9782,14 +9962,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: case 154 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -9803,9 +9983,9 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: case 154 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined @@ -9814,12 +9994,10 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isStringOrNumericLiteral(node) { - var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 8 /* NumericLiteral */; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); } - ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; /** * A declaration has a dynamic name if both of the following are true: * 1. The declaration has a computed property name @@ -9834,7 +10012,7 @@ var ts; ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { return name.kind === 147 /* ComputedPropertyName */ && - !isStringOrNumericLiteral(name.expression) && + !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -9848,22 +10026,24 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 /* Identifier */) { - return name.escapedText; - } - if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(name.text); - } - if (name.kind === 147 /* ComputedPropertyName */) { - var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(nameExpression.text); - } + switch (name.kind) { + case 71 /* Identifier */: + return name.escapedText; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 147 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); } - return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { @@ -9883,7 +10063,7 @@ var ts; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : escapeLeadingUnderscores(node.text); + return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -9911,7 +10091,7 @@ var ts; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 182 /* BindingElement */) { + while (node.kind === 184 /* BindingElement */) { node = node.parent.parent; } return node; @@ -9920,14 +10100,14 @@ var ts; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; return kind === 155 /* Constructor */ - || kind === 192 /* FunctionExpression */ - || kind === 234 /* FunctionDeclaration */ - || kind === 193 /* ArrowFunction */ + || kind === 194 /* FunctionExpression */ + || kind === 237 /* FunctionDeclaration */ + || kind === 195 /* ArrowFunction */ || kind === 154 /* MethodDeclaration */ || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */ - || kind === 239 /* ModuleDeclaration */ - || kind === 274 /* SourceFile */; + || kind === 242 /* ModuleDeclaration */ + || kind === 277 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -9946,23 +10126,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 188 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 188 /* NewExpression */: + case 190 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 198 /* PrefixUnaryExpression */: - case 195 /* TypeOfExpression */: - case 196 /* VoidExpression */: - case 194 /* DeleteExpression */: - case 197 /* AwaitExpression */: - case 201 /* ConditionalExpression */: - case 203 /* YieldExpression */: + case 200 /* PrefixUnaryExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 196 /* DeleteExpression */: + case 199 /* AwaitExpression */: + case 203 /* ConditionalExpression */: + case 205 /* YieldExpression */: return 1 /* Right */; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: switch (operator) { case 40 /* AsteriskAsteriskToken */: case 58 /* EqualsToken */: @@ -9986,15 +10166,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 188 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 200 /* BinaryExpression */) { + if (expression.kind === 202 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 198 /* PrefixUnaryExpression */ || expression.kind === 199 /* PostfixUnaryExpression */) { + else if (expression.kind === 200 /* PrefixUnaryExpression */ || expression.kind === 201 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -10004,15 +10184,15 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 302 /* CommaListExpression */: + case 307 /* CommaListExpression */: return 0; - case 204 /* SpreadElement */: + case 206 /* SpreadElement */: return 1; - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: return 2; - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return 4; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: switch (operatorKind) { case 26 /* CommaToken */: return 0; @@ -10033,21 +10213,21 @@ var ts; default: return getBinaryOperatorPrecedence(operatorKind); } - case 198 /* PrefixUnaryExpression */: - case 195 /* TypeOfExpression */: - case 196 /* VoidExpression */: - case 194 /* DeleteExpression */: - case 197 /* AwaitExpression */: + case 200 /* PrefixUnaryExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 196 /* DeleteExpression */: + case 199 /* AwaitExpression */: return 16; - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return 17; - case 187 /* CallExpression */: + case 189 /* CallExpression */: return 18; - case 188 /* NewExpression */: + case 190 /* NewExpression */: return hasArguments ? 19 : 18; - case 189 /* TaggedTemplateExpression */: - case 185 /* PropertyAccessExpression */: - case 186 /* ElementAccessExpression */: + case 191 /* TaggedTemplateExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return 19; case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: @@ -10057,19 +10237,19 @@ var ts; case 86 /* FalseKeyword */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - case 183 /* ArrayLiteralExpression */: - case 184 /* ObjectLiteralExpression */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: - case 205 /* ClassExpression */: - case 255 /* JsxElement */: - case 256 /* JsxSelfClosingElement */: - case 259 /* JsxFragment */: + case 185 /* ArrayLiteralExpression */: + case 186 /* ObjectLiteralExpression */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 207 /* ClassExpression */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 262 /* JsxFragment */: case 12 /* RegularExpressionLiteral */: case 13 /* NoSubstitutionTemplateLiteral */: - case 202 /* TemplateExpression */: - case 191 /* ParenthesizedExpression */: - case 206 /* OmittedExpression */: + case 204 /* TemplateExpression */: + case 193 /* ParenthesizedExpression */: + case 208 /* OmittedExpression */: return 20; default: return -1; @@ -10128,6 +10308,7 @@ var ts; var hasReadNonFileDiagnostics = false; return { add: add, + lookup: lookup, getGlobalDiagnostics: getGlobalDiagnostics, getDiagnostics: getDiagnostics, reattachFileDiagnostics: reattachFileDiagnostics @@ -10135,6 +10316,23 @@ var ts; function reattachFileDiagnostics(newFile) { ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); } + function lookup(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } + else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return undefined; + } + var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + return undefined; + } function add(diagnostic) { var diagnostics; if (diagnostic.file) { @@ -10320,8 +10518,8 @@ var ts; decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, - getLine: function () { return lineCount + 1; }, - getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, + getLine: function () { return lineCount; }, + getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, clear: reset, @@ -10357,34 +10555,37 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; - function getOwnEmitOutputFilePath(sourceFile, host, extension) { + function getOwnEmitOutputFilePath(fileName, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; if (compilerOptions.outDir) { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); } else { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); } return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; - function getDeclarationEmitOutputFilePath(sourceFile, host) { - var options = host.getCompilerOptions(); + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } - ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; /** * Gets the source files that are expected to have an emit output. * @@ -10416,14 +10617,17 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - var commonSourceDirectory = host.getCommonSourceDirectory(); - var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } - ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); @@ -10496,7 +10700,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 156 /* GetAccessor */ || member.kind === 157 /* SetAccessor */) + if (ts.isAccessor(member) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -10530,7 +10734,10 @@ var ts; * parsed in a JavaScript file, gets the type annotation from JSDoc. */ function getEffectiveTypeAnnotationNode(node) { - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); + var type = node.type; + if (type || !isInJavaScriptFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; function getTypeAnnotationNode(node) { @@ -10542,34 +10749,18 @@ var ts; * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { - if (ts.isJSDocSignature(node)) { - return node.type && node.type.typeExpression && node.type.typeExpression.type; - } - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - /** - * Gets the effective type parameters. If the node was parsed in a - * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. - */ - function getEffectiveTypeParameterDeclarations(node) { - if (ts.isJSDocSignature(node)) { - return ts.emptyArray; - } - if (isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 286 /* JSDocComment */); - return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); - } - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); - } - ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 286 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -10862,8 +11053,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 184 /* ObjectLiteralExpression */ - || kind === 183 /* ArrayLiteralExpression */; + return kind === 186 /* ObjectLiteralExpression */ + || kind === 185 /* ArrayLiteralExpression */; } return false; } @@ -10873,7 +11064,7 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 207 /* ExpressionWithTypeArguments */ + return node.kind === 209 /* ExpressionWithTypeArguments */ && isEntityNameExpression(node.expression) && node.parent && node.parent.token === 108 /* ImplementsKeyword */ @@ -10895,16 +11086,16 @@ var ts; ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 185 /* PropertyAccessExpression */ && node.parent.name === node); + (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 184 /* ObjectLiteralExpression */ && + return expression.kind === 186 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 183 /* ArrayLiteralExpression */ && + return expression.kind === 185 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -11245,8 +11436,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 238 /* EnumDeclaration */: - case 239 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -11265,6 +11456,10 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; function getCheckFlags(symbol) { return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } @@ -11319,21 +11514,23 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 199 /* PostfixUnaryExpression */: - case 198 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; - return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; - case 185 /* PropertyAccessExpression */: + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; + case 187 /* 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 === 216 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; } } function compareDataObjects(dst, src) { @@ -11436,7 +11633,7 @@ var ts; } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { - return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } ts.isUMDExportSymbol = isUMDExportSymbol; function showModuleSpecifier(_a) { @@ -11481,6 +11678,8 @@ var ts; switch (options.target) { case 6 /* ESNext */: return "lib.esnext.full.d.ts"; + case 5 /* ES2018 */: + return "lib.es2018.full.d.ts"; case 4 /* ES2017 */: return "lib.es2017.full.d.ts"; case 3 /* ES2016 */: @@ -11504,6 +11703,11 @@ var ts; return position >= span.start && position < textSpanEnd(span); } ts.textSpanContainsPosition = textSpanContainsPosition; + /* @internal */ + function textRangeContainsPositionInclusive(span, position) { + return position >= span.pos && position <= span.end; + } + ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive; // Returns true if 'span' contains 'other'. function textSpanContainsTextSpan(span, other) { return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); @@ -11697,7 +11901,7 @@ var ts; function getTypeParameterOwner(d) { if (d && d.kind === 148 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 236 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239 /* InterfaceDeclaration */) { return current; } } @@ -11722,27 +11926,34 @@ var ts; return isEmptyBindingPattern(node.name); } ts.isEmptyBindingElement = isEmptyBindingElement; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 182 /* BindingElement */ || ts.isBindingPattern(node))) { - node = node.parent; + function walkUpBindingElementsAndPatterns(binding) { + var node = binding.parent; + while (ts.isBindingElement(node.parent)) { + node = node.parent.parent; } - return node; + return node.parent; } - function getCombinedModifierFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = ts.getModifierFlags(node); - if (node.kind === 232 /* VariableDeclaration */) { + ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns; + function getCombinedFlags(node, getFlags) { + if (ts.isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + var flags = getFlags(node); + if (node.kind === 235 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 233 /* VariableDeclarationList */) { - flags |= ts.getModifierFlags(node); + if (node && node.kind === 236 /* VariableDeclarationList */) { + flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 214 /* VariableStatement */) { - flags |= ts.getModifierFlags(node); + if (node && node.kind === 217 /* VariableStatement */) { + flags |= getFlags(node); } return flags; } + function getCombinedModifierFlags(node) { + return getCombinedFlags(node, ts.getModifierFlags); + } ts.getCombinedModifierFlags = getCombinedModifierFlags; // Returns the node flags for this node and all relevant parent nodes. This is done so that // nodes like variable declarations and binding elements can returned a view of their flags @@ -11752,19 +11963,7 @@ var ts; // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = node.flags; - if (node.kind === 232 /* VariableDeclaration */) { - node = node.parent; - } - if (node && node.kind === 233 /* VariableDeclarationList */) { - flags |= node.flags; - node = node.parent; - } - if (node && node.kind === 214 /* VariableStatement */) { - flags |= node.flags; - } - return flags; + return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; /** @@ -11853,6 +12052,11 @@ var ts; return undefined; } ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; /** * Remove extra underscore from escaped identifier text content. * @@ -11872,16 +12076,6 @@ var ts; return unescapeLeadingUnderscores(symbol.escapedName); } ts.symbolName = symbolName; - /** - * Remove extra underscore from escaped identifier text content. - * @deprecated Use `id.text` for the unescaped text. - * @param identifier The escaped identifier text. - * @returns The unescaped identifier text. - */ - function unescapeIdentifier(id) { - 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 @@ -11898,17 +12092,17 @@ var ts; } // Covers remaining cases switch (hostNode.kind) { - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return expr.name; - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; @@ -11917,10 +12111,10 @@ var ts; return undefined; case 1 /* EndOfFileToken */: return undefined; - case 191 /* ParenthesizedExpression */: { + case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 228 /* LabeledStatement */: { + case 231 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -11932,7 +12126,7 @@ var ts; } function getDeclarationIdentifier(node) { var name = getNameOfDeclaration(node); - return ts.isIdentifier(name) ? name : undefined; + return name && ts.isIdentifier(name) ? name : undefined; } function getNameOfJSDocTypedef(declaration) { return declaration.name || nameForNamelessJSDocTypedef(declaration); @@ -11943,29 +12137,20 @@ var ts; return !!node.name; // A 'name' property should always be a DeclarationName. } ts.isNamedDeclaration = isNamedDeclaration; - // TODO: GH#18217 This is often used as if it returns a defined result - function getNameOfDeclaration(declaration) { - if (!declaration) { - return undefined; - } + /** @internal */ + function getNonAssignedNameOfDeclaration(declaration) { switch (declaration.kind) { - case 205 /* ClassExpression */: - case 192 /* FunctionExpression */: - if (!declaration.name) { - return getAssignedName(declaration); - } - break; case 71 /* Identifier */: return declaration; - case 298 /* JSDocPropertyTag */: - case 293 /* JSDocParameterTag */: { + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: { var name = declaration.name; if (name.kind === 146 /* QualifiedName */) { return name.right; } break; } - case 200 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var expr = declaration; switch (ts.getSpecialPropertyAssignmentKind(expr)) { case 1 /* ExportsProperty */: @@ -11977,17 +12162,22 @@ var ts; return undefined; } } - case 292 /* JSDocCallbackTag */: - return declaration.name; - case 297 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 249 /* ExportAssignment */: { + case 252 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } } return declaration.name; } + ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration; + function getNameOfDeclaration(declaration) { + if (declaration === undefined) + return undefined; + return getNonAssignedNameOfDeclaration(declaration) || + (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + } ts.getNameOfDeclaration = getNameOfDeclaration; function getAssignedName(node) { if (!node.parent) { @@ -12057,6 +12247,16 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node) { + return getFirstJSDocTag(node, ts.isJSDocThisTag); + } + ts.getJSDocThisTag = getJSDocThisTag; /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node) { return getFirstJSDocTag(node, ts.isJSDocReturnTag); @@ -12097,14 +12297,27 @@ var ts; } ts.getJSDocType = getJSDocType; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node) { var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } } ts.getJSDocReturnType = getJSDocReturnType; /** Get all JSDoc tags related to a node, including those on parent nodes. */ @@ -12128,6 +12341,28 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -12271,541 +12506,549 @@ var ts; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 169 /* UnionType */; + return node.kind === 171 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 170 /* IntersectionType */; + return node.kind === 172 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 171 /* ConditionalType */; + return node.kind === 173 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 172 /* InferType */; + return node.kind === 174 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 173 /* ParenthesizedType */; + return node.kind === 175 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 174 /* ThisType */; + return node.kind === 176 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 175 /* TypeOperator */; + return node.kind === 177 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 176 /* IndexedAccessType */; + return node.kind === 178 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 177 /* MappedType */; + return node.kind === 179 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 178 /* LiteralType */; + return node.kind === 180 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 179 /* ImportType */; + return node.kind === 181 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 180 /* ObjectBindingPattern */; + return node.kind === 182 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 181 /* ArrayBindingPattern */; + return node.kind === 183 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 182 /* BindingElement */; + return node.kind === 184 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 183 /* ArrayLiteralExpression */; + return node.kind === 185 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 184 /* ObjectLiteralExpression */; + return node.kind === 186 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 185 /* PropertyAccessExpression */; + return node.kind === 187 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 186 /* ElementAccessExpression */; + return node.kind === 188 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 187 /* CallExpression */; + return node.kind === 189 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 188 /* NewExpression */; + return node.kind === 190 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 189 /* TaggedTemplateExpression */; + return node.kind === 191 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 190 /* TypeAssertionExpression */; + return node.kind === 192 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 191 /* ParenthesizedExpression */; + return node.kind === 193 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 301 /* PartiallyEmittedExpression */) { + while (node.kind === 306 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 192 /* FunctionExpression */; + return node.kind === 194 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 193 /* ArrowFunction */; + return node.kind === 195 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 194 /* DeleteExpression */; + return node.kind === 196 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 195 /* TypeOfExpression */; + return node.kind === 197 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 196 /* VoidExpression */; + return node.kind === 198 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 197 /* AwaitExpression */; + return node.kind === 199 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 198 /* PrefixUnaryExpression */; + return node.kind === 200 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 199 /* PostfixUnaryExpression */; + return node.kind === 201 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 200 /* BinaryExpression */; + return node.kind === 202 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 201 /* ConditionalExpression */; + return node.kind === 203 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 202 /* TemplateExpression */; + return node.kind === 204 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 203 /* YieldExpression */; + return node.kind === 205 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 204 /* SpreadElement */; + return node.kind === 206 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 205 /* ClassExpression */; + return node.kind === 207 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 206 /* OmittedExpression */; + return node.kind === 208 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 207 /* ExpressionWithTypeArguments */; + return node.kind === 209 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 208 /* AsExpression */; + return node.kind === 210 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 209 /* NonNullExpression */; + return node.kind === 211 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 210 /* MetaProperty */; + return node.kind === 212 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 211 /* TemplateSpan */; + return node.kind === 214 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 212 /* SemicolonClassElement */; + return node.kind === 215 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 213 /* Block */; + return node.kind === 216 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 214 /* VariableStatement */; + return node.kind === 217 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 215 /* EmptyStatement */; + return node.kind === 218 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 216 /* ExpressionStatement */; + return node.kind === 219 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 217 /* IfStatement */; + return node.kind === 220 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 218 /* DoStatement */; + return node.kind === 221 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 219 /* WhileStatement */; + return node.kind === 222 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 220 /* ForStatement */; + return node.kind === 223 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 221 /* ForInStatement */; + return node.kind === 224 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 222 /* ForOfStatement */; + return node.kind === 225 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 223 /* ContinueStatement */; + return node.kind === 226 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 224 /* BreakStatement */; + return node.kind === 227 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isBreakOrContinueStatement(node) { - return node.kind === 224 /* BreakStatement */ || node.kind === 223 /* ContinueStatement */; + return node.kind === 227 /* BreakStatement */ || node.kind === 226 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 225 /* ReturnStatement */; + return node.kind === 228 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 226 /* WithStatement */; + return node.kind === 229 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 227 /* SwitchStatement */; + return node.kind === 230 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 228 /* LabeledStatement */; + return node.kind === 231 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 229 /* ThrowStatement */; + return node.kind === 232 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 230 /* TryStatement */; + return node.kind === 233 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 231 /* DebuggerStatement */; + return node.kind === 234 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 232 /* VariableDeclaration */; + return node.kind === 235 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 233 /* VariableDeclarationList */; + return node.kind === 236 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 234 /* FunctionDeclaration */; + return node.kind === 237 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 235 /* ClassDeclaration */; + return node.kind === 238 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 236 /* InterfaceDeclaration */; + return node.kind === 239 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 237 /* TypeAliasDeclaration */; + return node.kind === 240 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 238 /* EnumDeclaration */; + return node.kind === 241 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 239 /* ModuleDeclaration */; + return node.kind === 242 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 240 /* ModuleBlock */; + return node.kind === 243 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 241 /* CaseBlock */; + return node.kind === 244 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 242 /* NamespaceExportDeclaration */; + return node.kind === 245 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 243 /* ImportEqualsDeclaration */; + return node.kind === 246 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 244 /* ImportDeclaration */; + return node.kind === 247 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 245 /* ImportClause */; + return node.kind === 248 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 246 /* NamespaceImport */; + return node.kind === 249 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 247 /* NamedImports */; + return node.kind === 250 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 248 /* ImportSpecifier */; + return node.kind === 251 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 249 /* ExportAssignment */; + return node.kind === 252 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 250 /* ExportDeclaration */; + return node.kind === 253 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 251 /* NamedExports */; + return node.kind === 254 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 252 /* ExportSpecifier */; + return node.kind === 255 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 253 /* MissingDeclaration */; + return node.kind === 256 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 254 /* ExternalModuleReference */; + return node.kind === 257 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 255 /* JsxElement */; + return node.kind === 258 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 256 /* JsxSelfClosingElement */; + return node.kind === 259 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 257 /* JsxOpeningElement */; + return node.kind === 260 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 258 /* JsxClosingElement */; + return node.kind === 261 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 259 /* JsxFragment */; + return node.kind === 262 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 260 /* JsxOpeningFragment */; + return node.kind === 263 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 261 /* JsxClosingFragment */; + return node.kind === 264 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 262 /* JsxAttribute */; + return node.kind === 265 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 263 /* JsxAttributes */; + return node.kind === 266 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 264 /* JsxSpreadAttribute */; + return node.kind === 267 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 265 /* JsxExpression */; + return node.kind === 268 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 266 /* CaseClause */; + return node.kind === 269 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 267 /* DefaultClause */; + return node.kind === 270 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 268 /* HeritageClause */; + return node.kind === 271 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 269 /* CatchClause */; + return node.kind === 272 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 270 /* PropertyAssignment */; + return node.kind === 273 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 271 /* ShorthandPropertyAssignment */; + return node.kind === 274 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 272 /* SpreadAssignment */; + return node.kind === 275 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 273 /* EnumMember */; + return node.kind === 276 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 274 /* SourceFile */; + return node.kind === 277 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 275 /* Bundle */; + return node.kind === 278 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 276 /* UnparsedSource */; + return node.kind === 279 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 278 /* JSDocTypeExpression */; + return node.kind === 281 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 279 /* JSDocAllType */; + return node.kind === 282 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 280 /* JSDocUnknownType */; + return node.kind === 283 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 281 /* JSDocNullableType */; + return node.kind === 284 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 282 /* JSDocNonNullableType */; + return node.kind === 285 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 283 /* JSDocOptionalType */; + return node.kind === 286 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 284 /* JSDocFunctionType */; + return node.kind === 287 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 285 /* JSDocVariadicType */; + return node.kind === 288 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 286 /* JSDocComment */; + return node.kind === 289 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 290 /* JSDocAugmentsTag */; + return node.kind === 293 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 291 /* JSDocClassTag */; + return node.kind === 294 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 296 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; + function isJSDocThisTag(node) { + return node.kind === 299 /* JSDocThisTag */; + } + ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 293 /* JSDocParameterTag */; + return node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 294 /* JSDocReturnTag */; + return node.kind === 298 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 295 /* JSDocTypeTag */; + return node.kind === 300 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 296 /* JSDocTemplateTag */; + return node.kind === 301 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 297 /* JSDocTypedefTag */; + return node.kind === 302 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 298 /* JSDocPropertyTag */; + return node.kind === 303 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 298 /* JSDocPropertyTag */ || node.kind === 293 /* JSDocParameterTag */; + return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 287 /* JSDocTypeLiteral */; + return node.kind === 290 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocCallbackTag(node) { - return node.kind === 292 /* JSDocCallbackTag */; + return node.kind === 295 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocSignature(node) { - return node.kind === 288 /* JSDocSignature */; + return node.kind === 291 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); @@ -12816,7 +13059,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 299 /* SyntaxList */; + return n.kind === 304 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -12931,8 +13174,8 @@ var ts; function isBindingName(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 180 /* ObjectBindingPattern */ - || kind === 181 /* ArrayBindingPattern */; + || kind === 182 /* ObjectBindingPattern */ + || kind === 183 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -12947,13 +13190,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; default: return false; @@ -12964,11 +13207,11 @@ var ts; switch (kind) { case 153 /* MethodSignature */: case 158 /* CallSignature */: - case 288 /* JSDocSignature */: + case 291 /* JSDocSignature */: case 159 /* ConstructSignature */: case 160 /* IndexSignature */: case 163 /* FunctionType */: - case 284 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: case 164 /* ConstructorType */: return true; default: @@ -12990,11 +13233,11 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */ || kind === 160 /* IndexSignature */ - || kind === 212 /* SemicolonClassElement */; + || kind === 215 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 235 /* ClassDeclaration */ || node.kind === 205 /* ClassExpression */); + return node && (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { @@ -13029,9 +13272,9 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 270 /* PropertyAssignment */ - || kind === 271 /* ShorthandPropertyAssignment */ - || kind === 272 /* SpreadAssignment */ + return kind === 273 /* PropertyAssignment */ + || kind === 274 /* ShorthandPropertyAssignment */ + || kind === 275 /* SpreadAssignment */ || kind === 154 /* MethodDeclaration */ || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; @@ -13039,7 +13282,7 @@ var ts; ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type function isTypeNodeKind(kind) { - return (kind >= 161 /* FirstTypeNode */ && kind <= 179 /* LastTypeNode */) + return (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) || kind === 119 /* AnyKeyword */ || kind === 142 /* UnknownKeyword */ || kind === 134 /* NumberKeyword */ @@ -13052,14 +13295,14 @@ var ts; || kind === 140 /* UndefinedKeyword */ || kind === 95 /* NullKeyword */ || kind === 131 /* NeverKeyword */ - || kind === 207 /* ExpressionWithTypeArguments */ - || kind === 279 /* JSDocAllType */ - || kind === 280 /* JSDocUnknownType */ - || kind === 281 /* JSDocNullableType */ - || kind === 282 /* JSDocNonNullableType */ - || kind === 283 /* JSDocOptionalType */ - || kind === 284 /* JSDocFunctionType */ - || kind === 285 /* JSDocVariadicType */; + || kind === 209 /* ExpressionWithTypeArguments */ + || kind === 282 /* JSDocAllType */ + || kind === 283 /* JSDocUnknownType */ + || kind === 284 /* JSDocNullableType */ + || kind === 285 /* JSDocNonNullableType */ + || kind === 286 /* JSDocOptionalType */ + || kind === 287 /* JSDocFunctionType */ + || kind === 288 /* JSDocVariadicType */; } /** * Node test that determines whether a node is a valid type node. @@ -13084,8 +13327,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 181 /* ArrayBindingPattern */ - || kind === 180 /* ObjectBindingPattern */; + return kind === 183 /* ArrayBindingPattern */ + || kind === 182 /* ObjectBindingPattern */; } return false; } @@ -13093,15 +13336,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 183 /* ArrayLiteralExpression */ - || kind === 184 /* ObjectLiteralExpression */; + return kind === 185 /* ArrayLiteralExpression */ + || kind === 186 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 182 /* BindingElement */ - || kind === 206 /* OmittedExpression */; + return kind === 184 /* BindingElement */ + || kind === 208 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -13110,9 +13353,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: case 149 /* Parameter */: - case 182 /* BindingElement */: + case 184 /* BindingElement */: return true; } return false; @@ -13133,8 +13376,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 180 /* ObjectBindingPattern */: - case 184 /* ObjectLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 186 /* ObjectLiteralExpression */: return true; } return false; @@ -13146,8 +13389,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 181 /* ArrayBindingPattern */: - case 183 /* ArrayLiteralExpression */: + case 183 /* ArrayBindingPattern */: + case 185 /* ArrayLiteralExpression */: return true; } return false; @@ -13156,25 +13399,25 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 185 /* PropertyAccessExpression */ + return kind === 187 /* PropertyAccessExpression */ || kind === 146 /* QualifiedName */ - || kind === 179 /* ImportType */; + || kind === 181 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 185 /* PropertyAccessExpression */ + return kind === 187 /* PropertyAccessExpression */ || kind === 146 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 257 /* JsxOpeningElement */: - case 256 /* JsxSelfClosingElement */: - case 187 /* CallExpression */: - case 188 /* NewExpression */: - case 189 /* TaggedTemplateExpression */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 191 /* TaggedTemplateExpression */: case 150 /* Decorator */: return true; default: @@ -13183,12 +13426,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 187 /* CallExpression */ || node.kind === 188 /* NewExpression */; + return node.kind === 189 /* CallExpression */ || node.kind === 190 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 202 /* TemplateExpression */ + return kind === 204 /* TemplateExpression */ || kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -13199,32 +13442,32 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 185 /* PropertyAccessExpression */: - case 186 /* ElementAccessExpression */: - case 188 /* NewExpression */: - case 187 /* CallExpression */: - case 255 /* JsxElement */: - case 256 /* JsxSelfClosingElement */: - case 259 /* JsxFragment */: - case 189 /* TaggedTemplateExpression */: - case 183 /* ArrayLiteralExpression */: - case 191 /* ParenthesizedExpression */: - case 184 /* ObjectLiteralExpression */: - case 205 /* ClassExpression */: - case 192 /* FunctionExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + case 190 /* NewExpression */: + case 189 /* CallExpression */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 262 /* JsxFragment */: + case 191 /* TaggedTemplateExpression */: + case 185 /* ArrayLiteralExpression */: + case 193 /* ParenthesizedExpression */: + case 186 /* ObjectLiteralExpression */: + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: case 71 /* Identifier */: case 12 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 13 /* NoSubstitutionTemplateLiteral */: - case 202 /* TemplateExpression */: + case 204 /* TemplateExpression */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 99 /* ThisKeyword */: case 101 /* TrueKeyword */: case 97 /* SuperKeyword */: - case 209 /* NonNullExpression */: - case 210 /* MetaProperty */: + case 211 /* NonNullExpression */: + case 212 /* MetaProperty */: case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: @@ -13238,13 +13481,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 198 /* PrefixUnaryExpression */: - case 199 /* PostfixUnaryExpression */: - case 194 /* DeleteExpression */: - case 195 /* TypeOfExpression */: - case 196 /* VoidExpression */: - case 197 /* AwaitExpression */: - case 190 /* TypeAssertionExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 196 /* DeleteExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 199 /* AwaitExpression */: + case 192 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13253,9 +13496,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return true; - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; default: @@ -13274,15 +13517,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 201 /* ConditionalExpression */: - case 203 /* YieldExpression */: - case 193 /* ArrowFunction */: - case 200 /* BinaryExpression */: - case 204 /* SpreadElement */: - case 208 /* AsExpression */: - case 206 /* OmittedExpression */: - case 302 /* CommaListExpression */: - case 301 /* PartiallyEmittedExpression */: + case 203 /* ConditionalExpression */: + case 205 /* YieldExpression */: + case 195 /* ArrowFunction */: + case 202 /* BinaryExpression */: + case 206 /* SpreadElement */: + case 210 /* AsExpression */: + case 208 /* OmittedExpression */: + case 307 /* CommaListExpression */: + case 306 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13290,18 +13533,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 190 /* TypeAssertionExpression */ - || kind === 208 /* AsExpression */; + return kind === 192 /* TypeAssertionExpression */ + || kind === 210 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 301 /* PartiallyEmittedExpression */; + return node.kind === 306 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 300 /* NotEmittedStatement */; + return node.kind === 305 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13312,13 +13555,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 218 /* DoStatement */: - case 219 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return true; - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13326,7 +13569,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 221 /* ForInStatement */ || node.kind === 222 /* ForOfStatement */; + return node.kind === 224 /* ForInStatement */ || node.kind === 225 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13350,113 +13593,113 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 240 /* ModuleBlock */ - || kind === 239 /* ModuleDeclaration */ + return kind === 243 /* ModuleBlock */ + || kind === 242 /* ModuleDeclaration */ || kind === 71 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 240 /* ModuleBlock */ - || kind === 239 /* ModuleDeclaration */; + return kind === 243 /* ModuleBlock */ + || kind === 242 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 239 /* ModuleDeclaration */; + || kind === 242 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 247 /* NamedImports */ - || kind === 246 /* NamespaceImport */; + return kind === 250 /* NamedImports */ + || kind === 249 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 239 /* ModuleDeclaration */ || node.kind === 238 /* EnumDeclaration */; + return node.kind === 242 /* ModuleDeclaration */ || node.kind === 241 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 193 /* ArrowFunction */ - || kind === 182 /* BindingElement */ - || kind === 235 /* ClassDeclaration */ - || kind === 205 /* ClassExpression */ + return kind === 195 /* ArrowFunction */ + || kind === 184 /* BindingElement */ + || kind === 238 /* ClassDeclaration */ + || kind === 207 /* ClassExpression */ || kind === 155 /* Constructor */ - || kind === 238 /* EnumDeclaration */ - || kind === 273 /* EnumMember */ - || kind === 252 /* ExportSpecifier */ - || kind === 234 /* FunctionDeclaration */ - || kind === 192 /* FunctionExpression */ + || kind === 241 /* EnumDeclaration */ + || kind === 276 /* EnumMember */ + || kind === 255 /* ExportSpecifier */ + || kind === 237 /* FunctionDeclaration */ + || kind === 194 /* FunctionExpression */ || kind === 156 /* GetAccessor */ - || kind === 245 /* ImportClause */ - || kind === 243 /* ImportEqualsDeclaration */ - || kind === 248 /* ImportSpecifier */ - || kind === 236 /* InterfaceDeclaration */ - || kind === 262 /* JsxAttribute */ + || kind === 248 /* ImportClause */ + || kind === 246 /* ImportEqualsDeclaration */ + || kind === 251 /* ImportSpecifier */ + || kind === 239 /* InterfaceDeclaration */ + || kind === 265 /* JsxAttribute */ || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ - || kind === 239 /* ModuleDeclaration */ - || kind === 242 /* NamespaceExportDeclaration */ - || kind === 246 /* NamespaceImport */ + || kind === 242 /* ModuleDeclaration */ + || kind === 245 /* NamespaceExportDeclaration */ + || kind === 249 /* NamespaceImport */ || kind === 149 /* Parameter */ - || kind === 270 /* PropertyAssignment */ + || kind === 273 /* PropertyAssignment */ || kind === 152 /* PropertyDeclaration */ || kind === 151 /* PropertySignature */ || kind === 157 /* SetAccessor */ - || kind === 271 /* ShorthandPropertyAssignment */ - || kind === 237 /* TypeAliasDeclaration */ + || kind === 274 /* ShorthandPropertyAssignment */ + || kind === 240 /* TypeAliasDeclaration */ || kind === 148 /* TypeParameter */ - || kind === 232 /* VariableDeclaration */ - || kind === 297 /* JSDocTypedefTag */ - || kind === 292 /* JSDocCallbackTag */ - || kind === 298 /* JSDocPropertyTag */; + || kind === 235 /* VariableDeclaration */ + || kind === 302 /* JSDocTypedefTag */ + || kind === 295 /* JSDocCallbackTag */ + || kind === 303 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 234 /* FunctionDeclaration */ - || kind === 253 /* MissingDeclaration */ - || kind === 235 /* ClassDeclaration */ - || kind === 236 /* InterfaceDeclaration */ - || kind === 237 /* TypeAliasDeclaration */ - || kind === 238 /* EnumDeclaration */ - || kind === 239 /* ModuleDeclaration */ - || kind === 244 /* ImportDeclaration */ - || kind === 243 /* ImportEqualsDeclaration */ - || kind === 250 /* ExportDeclaration */ - || kind === 249 /* ExportAssignment */ - || kind === 242 /* NamespaceExportDeclaration */; + return kind === 237 /* FunctionDeclaration */ + || kind === 256 /* MissingDeclaration */ + || kind === 238 /* ClassDeclaration */ + || kind === 239 /* InterfaceDeclaration */ + || kind === 240 /* TypeAliasDeclaration */ + || kind === 241 /* EnumDeclaration */ + || kind === 242 /* ModuleDeclaration */ + || kind === 247 /* ImportDeclaration */ + || kind === 246 /* ImportEqualsDeclaration */ + || kind === 253 /* ExportDeclaration */ + || kind === 252 /* ExportAssignment */ + || kind === 245 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 224 /* BreakStatement */ - || kind === 223 /* ContinueStatement */ - || kind === 231 /* DebuggerStatement */ - || kind === 218 /* DoStatement */ - || kind === 216 /* ExpressionStatement */ - || kind === 215 /* EmptyStatement */ - || kind === 221 /* ForInStatement */ - || kind === 222 /* ForOfStatement */ - || kind === 220 /* ForStatement */ - || kind === 217 /* IfStatement */ - || kind === 228 /* LabeledStatement */ - || kind === 225 /* ReturnStatement */ - || kind === 227 /* SwitchStatement */ - || kind === 229 /* ThrowStatement */ - || kind === 230 /* TryStatement */ - || kind === 214 /* VariableStatement */ - || kind === 219 /* WhileStatement */ - || kind === 226 /* WithStatement */ - || kind === 300 /* NotEmittedStatement */ - || kind === 304 /* EndOfDeclarationMarker */ - || kind === 303 /* MergeDeclarationMarker */; + return kind === 227 /* BreakStatement */ + || kind === 226 /* ContinueStatement */ + || kind === 234 /* DebuggerStatement */ + || kind === 221 /* DoStatement */ + || kind === 219 /* ExpressionStatement */ + || kind === 218 /* EmptyStatement */ + || kind === 224 /* ForInStatement */ + || kind === 225 /* ForOfStatement */ + || kind === 223 /* ForStatement */ + || kind === 220 /* IfStatement */ + || kind === 231 /* LabeledStatement */ + || kind === 228 /* ReturnStatement */ + || kind === 230 /* SwitchStatement */ + || kind === 232 /* ThrowStatement */ + || kind === 233 /* TryStatement */ + || kind === 217 /* VariableStatement */ + || kind === 222 /* WhileStatement */ + || kind === 229 /* WithStatement */ + || kind === 305 /* NotEmittedStatement */ + || kind === 309 /* EndOfDeclarationMarker */ + || kind === 308 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 296 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -13483,10 +13726,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 213 /* Block */) + if (node.kind !== 216 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 230 /* TryStatement */ || node.parent.kind === 269 /* CatchClause */) { + if (node.parent.kind === 233 /* TryStatement */ || node.parent.kind === 272 /* CatchClause */) { return false; } } @@ -13496,7 +13739,7 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 254 /* ExternalModuleReference */ + return kind === 257 /* ExternalModuleReference */ || kind === 146 /* QualifiedName */ || kind === 71 /* Identifier */; } @@ -13507,62 +13750,62 @@ var ts; var kind = node.kind; return kind === 99 /* ThisKeyword */ || kind === 71 /* Identifier */ - || kind === 185 /* PropertyAccessExpression */; + || kind === 187 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 255 /* JsxElement */ - || kind === 265 /* JsxExpression */ - || kind === 256 /* JsxSelfClosingElement */ + return kind === 258 /* JsxElement */ + || kind === 268 /* JsxExpression */ + || kind === 259 /* JsxSelfClosingElement */ || kind === 10 /* JsxText */ - || kind === 259 /* JsxFragment */; + || kind === 262 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 262 /* JsxAttribute */ - || kind === 264 /* JsxSpreadAttribute */; + return kind === 265 /* JsxAttribute */ + || kind === 267 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 /* StringLiteral */ - || kind === 265 /* JsxExpression */; + || kind === 268 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 257 /* JsxOpeningElement */ - || kind === 256 /* JsxSelfClosingElement */; + return kind === 260 /* JsxOpeningElement */ + || kind === 259 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 266 /* CaseClause */ - || kind === 267 /* DefaultClause */; + return kind === 269 /* CaseClause */ + || kind === 270 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 278 /* FirstJSDocNode */ && node.kind <= 298 /* LastJSDocNode */; + return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 286 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 289 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 289 /* FirstJSDocTagNode */ && node.kind <= 298 /* LastJSDocTagNode */; + return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -13587,45 +13830,6 @@ var ts; return !!node.type; } ts.hasType = hasType; - /* True if the node could have a type node a `.type` */ - /* @internal */ - function couldHaveType(node) { - switch (node.kind) { - case 149 /* Parameter */: - case 151 /* PropertySignature */: - case 152 /* PropertyDeclaration */: - case 153 /* MethodSignature */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 173 /* ParenthesizedType */: - case 175 /* TypeOperator */: - case 177 /* MappedType */: - case 190 /* TypeAssertionExpression */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: - case 208 /* AsExpression */: - case 232 /* VariableDeclaration */: - case 234 /* FunctionDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 278 /* JSDocTypeExpression */: - case 281 /* JSDocNullableType */: - case 282 /* JSDocNonNullableType */: - case 283 /* JSDocOptionalType */: - case 284 /* JSDocFunctionType */: - case 285 /* JSDocVariadicType */: - return true; - } - return false; - } - ts.couldHaveType = couldHaveType; /** True if has initializer node attached to it. */ /* @internal */ function hasInitializer(node) { @@ -13639,23 +13843,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - switch (node.kind) { - case 262 /* JsxAttribute */: - case 264 /* JsxSpreadAttribute */: - case 270 /* PropertyAssignment */: - case 271 /* ShorthandPropertyAssignment */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return true; - default: - return false; - } + return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 162 /* TypeReference */ || node.kind === 207 /* ExpressionWithTypeArguments */; + return node.kind === 162 /* TypeReference */ || node.kind === 209 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13687,9 +13880,12 @@ var ts; return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isStringLiteralLike = isStringLiteralLike; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { /** @internal */ function isNamedImportsOrExports(node) { - return node.kind === 247 /* NamedImports */ || node.kind === 251 /* NamedExports */; + return node.kind === 250 /* NamedImports */ || node.kind === 254 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function Symbol(flags, name) { @@ -13703,7 +13899,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (Debug.isDebugging) { + if (ts.Debug.isDebugging) { this.checker = checker; } } @@ -13734,9 +13930,10 @@ var ts; getSignatureConstructor: function () { return Signature; }, getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; + /* @internal */ function formatStringFromArgs(text, args, baseIndex) { if (baseIndex === void 0) { baseIndex = 0; } - return text.replace(/{(\d+)}/g, function (_match, index) { return Debug.assertDefined(args[+index + baseIndex]); }); + return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; function getLocaleSpecificMessage(message) { @@ -13744,11 +13941,11 @@ var ts; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { - Debug.assertGreaterThanOrEqual(start, 0); - Debug.assertGreaterThanOrEqual(length, 0); + ts.Debug.assertGreaterThanOrEqual(start, 0); + ts.Debug.assertGreaterThanOrEqual(length, 0); if (file) { - Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(start + length, file.text.length); + ts.Debug.assertLessThanOrEqual(start, file.text.length); + ts.Debug.assertLessThanOrEqual(start + length, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -13790,6 +13987,7 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; + /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -13826,7 +14024,15 @@ var ts; function getDiagnosticFilePath(diagnostic) { return diagnostic.file ? diagnostic.file.path : undefined; } + /* @internal */ function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || + compareRelatedInformation(d1, d2) || + 0 /* EqualTo */; + } + ts.compareDiagnostics = compareDiagnostics; + /* @internal */ + function compareDiagnosticsSkipRelatedInformation(d1, d2) { return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || ts.compareValues(d1.start, d2.start) || ts.compareValues(d1.length, d2.length) || @@ -13834,7 +14040,19 @@ var ts; compareMessageText(d1.messageText, d2.messageText) || 0 /* EqualTo */; } - ts.compareDiagnostics = compareDiagnostics; + ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation; + function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0 /* EqualTo */; + } + if (d1.relatedInformation && d2.relatedInformation) { + return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) { + var d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared + }) || 0 /* EqualTo */; + } + return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; + } function compareMessageText(t1, t2) { var text1 = t1; var text2 = t2; @@ -13883,7 +14101,7 @@ var ts; } ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { - return !!(options.declaration && options.declarationMap); + return !!(getEmitDeclarations(options) && options.declarationMap); } ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { @@ -13903,6 +14121,14 @@ var ts; return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + if (oldOptions === newOptions) { + return false; + } + return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || + (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14040,7 +14266,7 @@ var ts; ts.getRootLength = getRootLength; // TODO(rbuckton): replace references with `resolvePath` function normalizePath(path) { - return resolvePath(path); + return ts.resolvePath(path); } ts.normalizePath = normalizePath; function normalizePathAndParts(path) { @@ -14048,7 +14274,7 @@ var ts; var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); if (parts.length) { var joinedParts = root + parts.join(ts.directorySeparator); - return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; } else { return { path: root, parts: parts }; @@ -14063,10 +14289,16 @@ var ts; return path; // return the leading portion of the path up to the last (non-terminal) directory separator // but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); + path = ts.removeTrailingDirectorySeparator(path); return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); } ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; function isUrl(path) { return getEncodedRootLength(path) < 0; } @@ -14091,10 +14323,11 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; + /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath - : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); } ts.convertToRelativePath = convertToRelativePath; function pathComponents(path, rootLength) { @@ -14112,7 +14345,7 @@ var ts; */ function getPathComponents(path, currentDirectory) { if (currentDirectory === void 0) { currentDirectory = ""; } - path = combinePaths(currentDirectory, path); + path = ts.combinePaths(currentDirectory, path); var rootLength = getRootLength(path); return pathComponents(path, rootLength); } @@ -14167,15 +14400,18 @@ var ts; function getPathFromPathComponents(pathComponents) { if (pathComponents.length === 0) return ""; - var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); if (pathComponents.length === 1) return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = reducePathComponents(getPathComponents(from)); - var toComponents = reducePathComponents(getPathComponents(to)); + var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); + var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); var start; for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { var fromComponent = getCanonicalFileName(fromComponents[start]); @@ -14194,26 +14430,27 @@ var ts; } return [""].concat(relative, components); } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); } ts.getRelativePathFromFile = getRelativePathFromFile; function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return getPathFromPathComponents(pathComponents); + return ts.getPathFromPathComponents(pathComponents); } ts.getRelativePathFromDirectory = getRelativePathFromDirectory; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; pathComponents[0] = prefix + firstComponent; } - return getPathFromPathComponents(pathComponents); + return ts.getPathFromPathComponents(pathComponents); } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; /** @@ -14221,19 +14458,19 @@ var ts; * with `./` or `../`) so as not to be confused with an unprefixed module name. */ function ensurePathIsNonModuleName(path) { - return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path; + return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; } ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; function getBaseFileName(path, extensions, ignoreCase) { - path = normalizeSlashes(path); + path = ts.normalizeSlashes(path); // if the path provided is itself the root, then it has not file name. - var rootLength = getRootLength(path); + var rootLength = ts.getRootLength(path); if (rootLength === path.length) return ""; // return the trailing portion of the path starting after the last (non-terminal) directory // separator but not including any trailing directory separator. path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; return extension ? name.slice(0, name.length - extension.length) : name; } @@ -14247,13 +14484,13 @@ var ts; paths[_i - 1] = arguments[_i]; } if (path) - path = normalizeSlashes(path); + path = ts.normalizeSlashes(path); for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { var relativePath = paths_1[_a]; if (!relativePath) continue; - relativePath = normalizeSlashes(relativePath); - if (!path || getRootLength(relativePath) !== 0) { + relativePath = ts.normalizeSlashes(relativePath); + if (!path || ts.getRootLength(relativePath) !== 0) { path = relativePath; } else { @@ -14272,8 +14509,8 @@ var ts; for (var _i = 1; _i < arguments.length; _i++) { paths[_i - 1] = arguments[_i]; } - var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path); - var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined))); + var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path); + var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; } ts.resolvePath = resolvePath; @@ -14308,8 +14545,8 @@ var ts; return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; - var aComponents = reducePathComponents(getPathComponents(a)); - var bComponents = reducePathComponents(getPathComponents(b)); + var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); + var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); for (var i = 0; i < sharedLength; i++) { var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; @@ -14357,8 +14594,8 @@ var ts; return false; if (parent === child) return true; - var parentComponents = reducePathComponents(getPathComponents(parent)); - var childComponents = reducePathComponents(getPathComponents(child)); + var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); + var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); if (childComponents.length < parentComponents.length) { return false; } @@ -14372,17 +14609,15 @@ var ts; return true; } ts.containsPath = containsPath; - function tryRemoveDirectoryPrefix(path, dirPath) { - var a = ts.tryRemovePrefix(path, dirPath); - if (a === undefined) - return undefined; - switch (a.charCodeAt(0)) { - case 47 /* slash */: - case 92 /* backslash */: - return a.slice(1); - default: - return undefined; - } + function isDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + function stripLeadingDirectorySeparator(s) { + return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + } + function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { + var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); + return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); } ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. @@ -14461,7 +14696,7 @@ var ts; var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; var hasWrittenComponent = false; - var components = getNormalizedPathComponents(spec, basePath); + var components = ts.getNormalizedPathComponents(spec, basePath); var lastComponent = ts.last(components); if (usage !== "exclude" && lastComponent === "**") { return undefined; @@ -14528,8 +14763,8 @@ var ts; } /** @param path directory of the tsconfig.json */ function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { - path = normalizePath(path); - currentDirectory = normalizePath(currentDirectory); + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); var absolutePath = combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), @@ -14546,8 +14781,8 @@ var ts; ts.getRegexFromPattern = getRegexFromPattern; /** @param path directory of the tsconfig.json */ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { - path = normalizePath(path); - currentDirectory = normalizePath(currentDirectory); + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); @@ -14614,7 +14849,7 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } @@ -14640,7 +14875,7 @@ var ts; // No "*" or "?" in the path return !hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); + : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -14817,7 +15052,7 @@ var ts; })(Debug = ts.Debug || (ts.Debug = {})); function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. - Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); var indexOfStar = pattern.indexOf("*"); return indexOfStar === -1 ? undefined : { prefix: pattern.substr(0, indexOfStar), @@ -14854,14 +15089,14 @@ var ts; } ts.isAnySupportedFileExtension = isAnySupportedFileExtension; function tryGetExtensionFromPath(path) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return ts.fileExtensionIs(path, e); }) || ts.find(ts.supportedJavascriptExtensions, function (e) { return ts.fileExtensionIs(path, e); }); + return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { if (typeof extensions === "string") extensions = [extensions]; - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; if (!ts.startsWith(extension, ".")) extension = "." + extension; if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { @@ -14916,6 +15151,100 @@ var ts; return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); } ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; })(ts || (ts = {})); var ts; (function (ts) { @@ -14935,7 +15264,7 @@ var ts; var SourceFileConstructor; // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 274 /* SourceFile */) { + if (kind === 277 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else if (kind === 71 /* Identifier */) { @@ -14999,14 +15328,14 @@ var ts; visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 272 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return visitNode(cbNode, node.expression); case 149 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || @@ -15031,20 +15360,20 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 182 /* BindingElement */: + case 184 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -15066,9 +15395,9 @@ var ts; case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 192 /* FunctionExpression */: - case 234 /* FunctionDeclaration */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -15093,290 +15422,288 @@ var ts; return visitNode(cbNode, node.elementType); case 168 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 169 /* UnionType */: - case 170 /* IntersectionType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 171 /* ConditionalType */: + case 173 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 172 /* InferType */: + case 174 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 179 /* ImportType */: + case 181 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 173 /* ParenthesizedType */: - case 175 /* TypeOperator */: + case 175 /* ParenthesizedType */: + case 177 /* TypeOperator */: return visitNode(cbNode, node.type); - case 176 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 177 /* MappedType */: + case 179 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 178 /* LiteralType */: + case 180 /* LiteralType */: return visitNode(cbNode, node.literal); - case 180 /* ObjectBindingPattern */: - case 181 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 187 /* CallExpression */: - case 188 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 190 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 194 /* DeleteExpression */: + case 196 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 195 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 196 /* VoidExpression */: + case 198 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 197 /* AwaitExpression */: + case 199 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 208 /* AsExpression */: + case 210 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 209 /* NonNullExpression */: + case 211 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 210 /* MetaProperty */: + case 212 /* MetaProperty */: return visitNode(cbNode, node.name); - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 204 /* SpreadElement */: + case 206 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 213 /* Block */: - case 240 /* ModuleBlock */: + case 216 /* Block */: + case 243 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 274 /* SourceFile */: + case 277 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 233 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 217 /* IfStatement */: + case 220 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 218 /* DoStatement */: + case 221 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 219 /* WhileStatement */: + case 222 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 223 /* ContinueStatement */: - case 224 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: return visitNode(cbNode, node.label); - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 226 /* WithStatement */: + case 229 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 266 /* CaseClause */: + case 269 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 267 /* DefaultClause */: + case 270 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 229 /* ThrowStatement */: + case 232 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 230 /* TryStatement */: + case 233 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); case 150 /* Decorator */: return visitNode(cbNode, node.expression); - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 273 /* EnumMember */: + case 276 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 245 /* ImportClause */: + case 248 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 242 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 246 /* NamespaceImport */: + case 249 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 247 /* NamedImports */: - case 251 /* NamedExports */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 248 /* ImportSpecifier */: - case 252 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 202 /* TemplateExpression */: + case 204 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 211 /* TemplateSpan */: + case 214 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); case 147 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 268 /* HeritageClause */: + case 271 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 254 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 253 /* MissingDeclaration */: + case 256 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 302 /* CommaListExpression */: + case 307 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 255 /* JsxElement */: + case 258 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 259 /* JsxFragment */: + case 262 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 256 /* JsxSelfClosingElement */: - case 257 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 263 /* JsxAttributes */: + case 266 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 262 /* JsxAttribute */: + case 265 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 264 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 265 /* JsxExpression */: + case 268 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 258 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 278 /* JSDocTypeExpression */: + case 169 /* OptionalType */: + case 170 /* RestType */: + case 281 /* JSDocTypeExpression */: + case 285 /* JSDocNonNullableType */: + case 284 /* JSDocNullableType */: + case 286 /* JSDocOptionalType */: + case 288 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 282 /* JSDocNonNullableType */: - return visitNode(cbNode, node.type); - case 281 /* JSDocNullableType */: - return visitNode(cbNode, node.type); - case 283 /* JSDocOptionalType */: - return visitNode(cbNode, node.type); - case 284 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 285 /* JSDocVariadicType */: - return visitNode(cbNode, node.type); - case 286 /* JSDocComment */: + case 289 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 293 /* JSDocParameterTag */: - case 298 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15385,17 +15712,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 294 /* JSDocReturnTag */: + case 298 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 295 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 290 /* JSDocAugmentsTag */: + case 293 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 296 /* JSDocTemplateTag */: - return visitNodes(cbNode, cbNodes, node.typeParameters); - case 297 /* JSDocTypedefTag */: + case 301 /* JSDocTemplateTag */: + return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); + case 302 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 278 /* JSDocTypeExpression */) { + node.typeExpression.kind === 281 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -15403,16 +15730,20 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 292 /* JSDocCallbackTag */: + case 295 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 288 /* JSDocSignature */: + case 299 /* JSDocThisTag */: + return visitNode(cbNode, node.typeExpression); + case 296 /* JSDocEnumTag */: + return visitNode(cbNode, node.typeExpression); + case 291 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || + ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 287 /* JSDocTypeLiteral */: + case 290 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -15420,7 +15751,7 @@ var ts; } } return; - case 301 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15634,7 +15965,7 @@ var ts; sourceFile.endOfFileToken = parseTokenNode(); } else { - var statement = createNode(216 /* ExpressionStatement */); + var statement = createNode(219 /* ExpressionStatement */); switch (token()) { case 21 /* OpenBracketToken */: statement.expression = parseArrayLiteralExpression(); @@ -15751,13 +16082,10 @@ var ts; } } function addJSDocComment(node) { - var comments = ts.getJSDocCommentRanges(node, sourceFile.text); - if (comments) { - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var comment = comments_2[_i]; - node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); - } - } + ts.Debug.assert(!node.jsDoc); // Should only be called once per node + var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); }); + if (jsDoc.length) + node.jsDoc = jsDoc; return node; } function fixupParentReferences(rootNode) { @@ -15793,7 +16121,7 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(274 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(277 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -16272,7 +16600,7 @@ var ts; return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); @@ -16295,7 +16623,7 @@ var ts; return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: if (token() === 26 /* CommaToken */) { @@ -16305,13 +16633,15 @@ var ts; case 11 /* ArgumentExpressions */: return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: - return isStartOfParameter(); - case 19 /* TypeArguments */: - case 20 /* TupleElementTypes */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: return token() === 26 /* CommaToken */ || isStartOfType(); - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return isHeritageClause(); - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; @@ -16376,7 +16706,7 @@ var ts; case 6 /* EnumMembers */: case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return token() === 18 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; @@ -16384,24 +16714,25 @@ var ts; return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: return token() === 22 /* CloseBracketToken */; + case 17 /* JSDocParameters */: case 16 /* Parameters */: - case 17 /* RestProperties */: + case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token return token() !== 26 /* CommaToken */; - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; case 13 /* JsxAttributes */: return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; @@ -16434,7 +16765,7 @@ var ts; } // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 23 /* Count */; kind++) { + for (var kind = 0; kind < 24 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; @@ -16546,24 +16877,25 @@ var ts; return isReusableTypeMember(node); case 8 /* VariableDeclarations */: return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -16571,7 +16903,7 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. @@ -16600,7 +16932,7 @@ var ts; case 156 /* GetAccessor */: case 157 /* SetAccessor */: case 152 /* PropertyDeclaration */: - case 212 /* SemicolonClassElement */: + case 215 /* SemicolonClassElement */: return true; case 154 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal @@ -16617,8 +16949,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 266 /* CaseClause */: - case 267 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: return true; } } @@ -16627,42 +16959,42 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 234 /* FunctionDeclaration */: - case 214 /* VariableStatement */: - case 213 /* Block */: - case 217 /* IfStatement */: - case 216 /* ExpressionStatement */: - case 229 /* ThrowStatement */: - case 225 /* ReturnStatement */: - case 227 /* SwitchStatement */: - case 224 /* BreakStatement */: - case 223 /* ContinueStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 220 /* ForStatement */: - case 219 /* WhileStatement */: - case 226 /* WithStatement */: - case 215 /* EmptyStatement */: - case 230 /* TryStatement */: - case 228 /* LabeledStatement */: - case 218 /* DoStatement */: - case 231 /* DebuggerStatement */: - case 244 /* ImportDeclaration */: - case 243 /* ImportEqualsDeclaration */: - case 250 /* ExportDeclaration */: - case 249 /* ExportAssignment */: - case 239 /* ModuleDeclaration */: - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 238 /* EnumDeclaration */: - case 237 /* TypeAliasDeclaration */: + case 237 /* FunctionDeclaration */: + case 217 /* VariableStatement */: + case 216 /* Block */: + case 220 /* IfStatement */: + case 219 /* ExpressionStatement */: + case 232 /* ThrowStatement */: + case 228 /* ReturnStatement */: + case 230 /* SwitchStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 223 /* ForStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: + case 218 /* EmptyStatement */: + case 233 /* TryStatement */: + case 231 /* LabeledStatement */: + case 221 /* DoStatement */: + case 234 /* DebuggerStatement */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 273 /* EnumMember */; + return node.kind === 276 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { @@ -16678,7 +17010,7 @@ var ts; return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 232 /* VariableDeclaration */) { + if (node.kind !== 235 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -16721,7 +17053,7 @@ var ts; case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected; case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; - case 17 /* RestProperties */: // fallthrough + case 18 /* RestProperties */: // fallthrough case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; @@ -16732,12 +17064,13 @@ var ts; case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected; case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; + case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected; case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 18 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; - case 19 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 20 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; - case 21 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; - case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; + case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; + case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; + case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` @@ -16804,7 +17137,12 @@ var ts; return result; } function createMissingList() { - return createNodeArray([], getNodePos()); + var list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -16866,7 +17204,7 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(202 /* TemplateExpression */); + var template = createNode(204 /* TemplateExpression */); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); var list = []; @@ -16878,7 +17216,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(211 /* TemplateSpan */); + var span = createNode(214 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token() === 18 /* CloseBraceToken */) { @@ -16932,7 +17270,7 @@ var ts; var node = createNode(162 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } return finishNode(node); } @@ -16944,10 +17282,9 @@ var ts; case 163 /* FunctionType */: case 164 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; - // parameters.pos === parameters.end only if we used parseMissingList, else should contain at least `()` - return parameters.pos === parameters.end || typeHasArrowFunctionBlockingParseError(type); + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 173 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -16961,14 +17298,14 @@ var ts; return finishNode(node); } function parseThisTypeNode() { - var node = createNode(174 /* ThisType */); + var node = createNode(176 /* ThisType */); nextToken(); return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(279 /* JSDocAllType */); + var result = createNode(282 /* JSDocAllType */); if (postFixEquals) { - return createJSDocPostfixType(283 /* JSDocOptionalType */, result); + return createPostfixType(286 /* JSDocOptionalType */, result); } else { nextToken(); @@ -16976,7 +17313,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(282 /* JSDocNonNullableType */); + var result = createNode(285 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -17000,18 +17337,18 @@ var ts; token() === 29 /* GreaterThanToken */ || token() === 58 /* EqualsToken */ || token() === 49 /* BarToken */) { - var result = createNode(280 /* JSDocUnknownType */, pos); + var result = createNode(283 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(281 /* JSDocNullableType */, pos); + var result = createNode(284 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(284 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(287 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); @@ -17031,14 +17368,14 @@ var ts; } function parseJSDocType() { var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); - var type = parseType(); + var type = parseTypeOrTypePredicate(); if (dotdotdot) { - var variadic = createNode(285 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } if (token() === 58 /* EqualsToken */) { - return createJSDocPostfixType(283 /* JSDocOptionalType */, type); + return createPostfixType(286 /* JSDocOptionalType */, type); } return type; } @@ -17077,7 +17414,7 @@ var ts; } function parseTypeParameters() { if (token() === 27 /* LessThanToken */) { - return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } } function parseParameterType() { @@ -17086,12 +17423,12 @@ var ts; } return undefined; } - function isStartOfParameter() { + function isStartOfParameter(isJSDocParameter) { return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 /* AtToken */ || - isStartOfType(/*inStartOfParameter*/ true); + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { var node = createNodeWithJSDoc(149 /* Parameter */); @@ -17177,7 +17514,9 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1 /* Yield */)); setAwaitContext(!!(flags & 2 /* Await */)); - signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return parseExpected(20 /* CloseParenToken */); @@ -17378,7 +17717,7 @@ var ts; return finishNode(node); } function parseMappedType() { - var node = createNode(177 /* MappedType */); + var node = createNode(179 /* MappedType */); parseExpected(17 /* OpenBraceToken */); if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { node.readonlyToken = parseTokenNode(); @@ -17400,13 +17739,26 @@ var ts; parseExpected(18 /* CloseBraceToken */); return finishNode(node); } + function parseTupleElementType() { + var pos = getNodePos(); + if (parseOptional(24 /* DotDotDotToken */)) { + var node = createNode(170 /* RestType */, pos); + node.type = parseType(); + return finishNode(node); + } + var type = parseType(); + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 284 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 169 /* OptionalType */; + } + return type; + } function parseTupleType() { var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(173 /* ParenthesizedType */); + var node = createNode(175 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); parseExpected(20 /* CloseParenToken */); @@ -17424,10 +17776,10 @@ var ts; return token() === 23 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(178 /* LiteralType */); + var node = createNode(180 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(198 /* PrefixUnaryExpression */); + unaryMinusExpression = createNode(200 /* PrefixUnaryExpression */); unaryMinusExpression.operator = 38 /* MinusToken */; nextToken(); } @@ -17448,7 +17800,7 @@ var ts; } function parseImportType() { sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; - var node = createNode(179 /* ImportType */); + var node = createNode(181 /* ImportType */); if (parseOptional(103 /* TypeOfKeyword */)) { node.isTypeOf = true; } @@ -17555,6 +17907,8 @@ var ts; case 126 /* InferKeyword */: case 91 /* ImportKeyword */: return true; + case 89 /* FunctionKeyword */: + return !inStartOfParameter; case 38 /* MinusToken */: return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19 /* OpenParenToken */: @@ -17567,26 +17921,26 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { case 51 /* ExclamationToken */: - type = createJSDocPostfixType(282 /* JSDocNonNullableType */, type); + type = createPostfixType(285 /* JSDocNonNullableType */, type); break; case 55 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createJSDocPostfixType(281 /* JSDocNullableType */, type); + type = createPostfixType(284 /* JSDocNullableType */, type); break; case 21 /* OpenBracketToken */: parseExpected(21 /* OpenBracketToken */); if (isStartOfType()) { - var node = createNode(176 /* IndexedAccessType */, type.pos); + var node = createNode(178 /* IndexedAccessType */, type.pos); node.objectType = type; node.indexType = parseType(); parseExpected(22 /* CloseBracketToken */); @@ -17605,21 +17959,21 @@ var ts; } return type; } - function createJSDocPostfixType(kind, type) { + function createPostfixType(kind, type) { nextToken(); var postfix = createNode(kind, type.pos); postfix.type = type; return finishNode(postfix); } function parseTypeOperator(operator) { - var node = createNode(175 /* TypeOperator */); + var node = createNode(177 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseInferType() { - var node = createNode(172 /* InferType */); + var node = createNode(174 /* InferType */); parseExpected(126 /* InferKeyword */); var typeParameter = createNode(148 /* TypeParameter */); typeParameter.name = parseIdentifier(); @@ -17652,10 +18006,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(170 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(172 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(169 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(171 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); } function isStartOfFunctionType() { if (token() === 27 /* LessThanToken */) { @@ -17739,7 +18093,7 @@ var ts; } var type = parseUnionTypeOrHigher(); if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { - var node = createNode(171 /* ConditionalType */, type.pos); + var node = createNode(173 /* ConditionalType */, type.pos); node.checkType = type; // The type following 'extends' is not permitted to be another conditional type node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); @@ -17932,7 +18286,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(203 /* YieldExpression */); + var node = createNode(205 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -17954,11 +18308,11 @@ var ts; ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(193 /* ArrowFunction */, asyncModifier.pos); + node = createNode(195 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(193 /* ArrowFunction */, identifier.pos); + node = createNode(195 /* ArrowFunction */, identifier.pos); } var parameter = createNode(149 /* Parameter */, identifier.pos); parameter.name = identifier; @@ -18061,8 +18415,9 @@ var ts; return 1 /* True */; } // If we had "(" followed by something that's not an identifier, - // then this definitely doesn't look like a lambda. - if (!isIdentifier()) { + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 99 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { @@ -18156,7 +18511,7 @@ var ts; return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNodeWithJSDoc(193 /* ArrowFunction */); + var node = createNodeWithJSDoc(195 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -18220,7 +18575,7 @@ var ts; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(201 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(203 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -18300,39 +18655,39 @@ var ts; return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(200 /* BinaryExpression */, left.pos); + var node = createNode(202 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(208 /* AsExpression */, left.pos); + var node = createNode(210 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(198 /* PrefixUnaryExpression */); + var node = createNode(200 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(194 /* DeleteExpression */); + var node = createNode(196 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(195 /* TypeOfExpression */); + var node = createNode(197 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(196 /* VoidExpression */); + var node = createNode(198 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -18348,7 +18703,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(197 /* AwaitExpression */); + var node = createNode(199 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -18392,7 +18747,7 @@ var ts; if (token() === 40 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 190 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 192 /* TypeAssertionExpression */) { parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -18489,7 +18844,7 @@ var ts; */ function parseUpdateExpression() { if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(198 /* PrefixUnaryExpression */); + var node = createNode(200 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -18502,7 +18857,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(199 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(201 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -18558,7 +18913,7 @@ var ts; var fullStart = scanner.getStartPos(); nextToken(); // advance past the 'import' nextToken(); // advance past the dot - var node = createNode(210 /* MetaProperty */, fullStart); + var node = createNode(212 /* MetaProperty */, fullStart); node.keywordToken = 91 /* ImportKeyword */; node.name = parseIdentifierName(); expression = finishNode(node); @@ -18633,7 +18988,7 @@ var ts; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(185 /* PropertyAccessExpression */, expression.pos); + var node = createNode(187 /* PropertyAccessExpression */, expression.pos); node.expression = expression; parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -18642,8 +18997,8 @@ var ts; function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 257 /* JsxOpeningElement */) { - var node = createNode(255 /* JsxElement */, opening.pos); + if (opening.kind === 260 /* JsxOpeningElement */) { + var node = createNode(258 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); @@ -18652,15 +19007,15 @@ var ts; } result = finishNode(node); } - else if (opening.kind === 260 /* JsxOpeningFragment */) { - var node = createNode(259 /* JsxFragment */, opening.pos); + else if (opening.kind === 263 /* JsxOpeningFragment */) { + var node = createNode(262 /* JsxFragment */, opening.pos); node.openingFragment = opening; node.children = parseJsxChildren(node.openingFragment); node.closingFragment = parseJsxClosingFragment(inExpressionContext); result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 256 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 259 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -18675,7 +19030,7 @@ var ts; var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(200 /* BinaryExpression */, result.pos); + var badNode = createNode(202 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -18733,7 +19088,7 @@ var ts; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(263 /* JsxAttributes */); + var jsxAttributes = createNode(266 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } @@ -18742,7 +19097,7 @@ var ts; parseExpected(27 /* LessThanToken */); if (token() === 29 /* GreaterThanToken */) { // See below for explanation of scanJsxText - var node_1 = createNode(260 /* JsxOpeningFragment */, fullStart); + var node_1 = createNode(263 /* JsxOpeningFragment */, fullStart); scanJsxText(); return finishNode(node_1); } @@ -18754,7 +19109,7 @@ var ts; // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(257 /* JsxOpeningElement */, fullStart); + node = createNode(260 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -18766,7 +19121,7 @@ var ts; parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(256 /* JsxSelfClosingElement */, fullStart); + node = createNode(259 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.typeArguments = typeArguments; @@ -18783,7 +19138,7 @@ var ts; var expression = token() === 99 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(185 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -18791,7 +19146,7 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(265 /* JsxExpression */); + var node = createNode(268 /* JsxExpression */); if (!parseExpected(17 /* OpenBraceToken */)) { return undefined; } @@ -18813,7 +19168,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(262 /* JsxAttribute */); + var node = createNode(265 /* JsxAttribute */); node.name = parseIdentifierName(); if (token() === 58 /* EqualsToken */) { switch (scanJsxAttributeValue()) { @@ -18828,7 +19183,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(264 /* JsxSpreadAttribute */); + var node = createNode(267 /* JsxSpreadAttribute */); parseExpected(17 /* OpenBraceToken */); parseExpected(24 /* DotDotDotToken */); node.expression = parseExpression(); @@ -18836,7 +19191,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(258 /* JsxClosingElement */); + var node = createNode(261 /* JsxClosingElement */); parseExpected(28 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -18849,7 +19204,7 @@ var ts; return finishNode(node); } function parseJsxClosingFragment(inExpressionContext) { - var node = createNode(261 /* JsxClosingFragment */); + var node = createNode(264 /* JsxClosingFragment */); parseExpected(28 /* LessThanSlashToken */); if (ts.tokenIsIdentifierOrKeyword(token())) { parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); @@ -18864,7 +19219,7 @@ var ts; return finishNode(node); } function parseTypeAssertion() { - var node = createNode(190 /* TypeAssertionExpression */); + var node = createNode(192 /* TypeAssertionExpression */); parseExpected(27 /* LessThanToken */); node.type = parseType(); parseExpected(29 /* GreaterThanToken */); @@ -18875,7 +19230,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(23 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(185 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -18883,21 +19238,21 @@ var ts; } if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(209 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(211 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(186 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(188 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; if (token() === 22 /* CloseBracketToken */) { indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); } else { var argument = allowInAnd(parseExpression); - if (ts.isStringOrNumericLiteral(argument)) { + if (ts.isStringOrNumericLiteralLike(argument)) { argument.text = internIdentifier(argument.text); } indexedAccess.argumentExpression = argument; @@ -18917,7 +19272,7 @@ var ts; return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */; } function parseTaggedTemplateRest(tag, typeArguments) { - var tagExpression = createNode(189 /* TaggedTemplateExpression */, tag.pos); + var tagExpression = createNode(191 /* TaggedTemplateExpression */, tag.pos); tagExpression.tag = tag; tagExpression.typeArguments = typeArguments; tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ @@ -18941,7 +19296,7 @@ var ts; expression = parseTaggedTemplateRest(expression, typeArguments); continue; } - var callExpr = createNode(187 /* CallExpression */, expression.pos); + var callExpr = createNode(189 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -18949,7 +19304,7 @@ var ts; continue; } else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(187 /* CallExpression */, expression.pos); + var callExpr = createNode(189 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -18968,7 +19323,7 @@ var ts; if (!parseOptional(27 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; @@ -19061,28 +19416,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNodeWithJSDoc(191 /* ParenthesizedExpression */); + var node = createNodeWithJSDoc(193 /* ParenthesizedExpression */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(204 /* SpreadElement */); + var node = createNode(206 /* SpreadElement */); parseExpected(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(206 /* OmittedExpression */) : + token() === 26 /* CommaToken */ ? createNode(208 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(183 /* ArrayLiteralExpression */); + var node = createNode(185 /* ArrayLiteralExpression */); parseExpected(21 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -19094,7 +19449,7 @@ var ts; function parseObjectLiteralElement() { var node = createNodeWithJSDoc(0 /* Unknown */); if (parseOptionalToken(24 /* DotDotDotToken */)) { - node.kind = 272 /* SpreadAssignment */; + node.kind = 275 /* SpreadAssignment */; node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } @@ -19121,7 +19476,7 @@ var ts; // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); if (isShorthandPropertyAssignment) { - node.kind = 271 /* ShorthandPropertyAssignment */; + node.kind = 274 /* ShorthandPropertyAssignment */; var equalsToken = parseOptionalToken(58 /* EqualsToken */); if (equalsToken) { node.equalsToken = equalsToken; @@ -19129,14 +19484,14 @@ var ts; } } else { - node.kind = 270 /* PropertyAssignment */; + node.kind = 273 /* PropertyAssignment */; parseExpected(56 /* ColonToken */); node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(184 /* ObjectLiteralExpression */); + var node = createNode(186 /* ObjectLiteralExpression */); parseExpected(17 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -19155,7 +19510,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNodeWithJSDoc(192 /* FunctionExpression */); + var node = createNodeWithJSDoc(194 /* FunctionExpression */); node.modifiers = parseModifiers(); parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); @@ -19180,7 +19535,7 @@ var ts; var fullStart = scanner.getStartPos(); parseExpected(94 /* NewKeyword */); if (parseOptional(23 /* DotToken */)) { - var node_2 = createNode(210 /* MetaProperty */, fullStart); + var node_2 = createNode(212 /* MetaProperty */, fullStart); node_2.keywordToken = 94 /* NewKeyword */; node_2.name = parseIdentifierName(); return finishNode(node_2); @@ -19197,7 +19552,7 @@ var ts; } break; } - var node = createNode(188 /* NewExpression */, fullStart); + var node = createNode(190 /* NewExpression */, fullStart); node.expression = expression; node.typeArguments = typeArguments; if (node.typeArguments || token() === 19 /* OpenParenToken */) { @@ -19207,7 +19562,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(213 /* Block */); + var node = createNode(216 /* Block */); if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -19240,12 +19595,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(215 /* EmptyStatement */); + var node = createNode(218 /* EmptyStatement */); parseExpected(25 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(217 /* IfStatement */); + var node = createNode(220 /* IfStatement */); parseExpected(90 /* IfKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -19255,7 +19610,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(218 /* DoStatement */); + var node = createNode(221 /* DoStatement */); parseExpected(81 /* DoKeyword */); node.statement = parseStatement(); parseExpected(106 /* WhileKeyword */); @@ -19270,7 +19625,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(219 /* WhileStatement */); + var node = createNode(222 /* WhileStatement */); parseExpected(106 /* WhileKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -19294,7 +19649,7 @@ var ts; } var forOrForInOrForOfStatement; if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) { - var forOfStatement = createNode(222 /* ForOfStatement */, pos); + var forOfStatement = createNode(225 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); @@ -19302,14 +19657,14 @@ var ts; forOrForInOrForOfStatement = forOfStatement; } else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(221 /* ForInStatement */, pos); + var forInStatement = createNode(224 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(220 /* ForStatement */, pos); + var forStatement = createNode(223 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(25 /* SemicolonToken */); if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { @@ -19327,7 +19682,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 224 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 227 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -19335,7 +19690,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(225 /* ReturnStatement */); + var node = createNode(228 /* ReturnStatement */); parseExpected(96 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -19344,7 +19699,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(226 /* WithStatement */); + var node = createNode(229 /* WithStatement */); parseExpected(107 /* WithKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -19353,7 +19708,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(266 /* CaseClause */); + var node = createNode(269 /* CaseClause */); parseExpected(73 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(56 /* ColonToken */); @@ -19361,7 +19716,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(267 /* DefaultClause */); + var node = createNode(270 /* DefaultClause */); parseExpected(79 /* DefaultKeyword */); parseExpected(56 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -19371,12 +19726,12 @@ var ts; return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(227 /* SwitchStatement */); + var node = createNode(230 /* SwitchStatement */); parseExpected(98 /* SwitchKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(241 /* CaseBlock */); + var caseBlock = createNode(244 /* CaseBlock */); parseExpected(17 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(18 /* CloseBraceToken */); @@ -19391,7 +19746,7 @@ var ts; // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - var node = createNode(229 /* ThrowStatement */); + var node = createNode(232 /* ThrowStatement */); parseExpected(100 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -19399,7 +19754,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(230 /* TryStatement */); + var node = createNode(233 /* TryStatement */); parseExpected(102 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -19412,7 +19767,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(269 /* CatchClause */); + var result = createNode(272 /* CatchClause */); parseExpected(74 /* CatchKeyword */); if (parseOptional(19 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -19426,7 +19781,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(231 /* DebuggerStatement */); + var node = createNode(234 /* DebuggerStatement */); parseExpected(78 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -19438,12 +19793,12 @@ var ts; var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - node.kind = 228 /* LabeledStatement */; + node.kind = 231 /* LabeledStatement */; node.label = expression; node.statement = parseStatement(); } else { - node.kind = 216 /* ExpressionStatement */; + node.kind = 219 /* ExpressionStatement */; node.expression = expression; parseSemicolon(); } @@ -19610,16 +19965,16 @@ var ts; case 17 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); case 104 /* VarKeyword */: - return parseVariableStatement(createNodeWithJSDoc(232 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); case 110 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(createNodeWithJSDoc(232 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); } break; case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(createNodeWithJSDoc(234 /* FunctionDeclaration */)); + return parseFunctionDeclaration(createNodeWithJSDoc(237 /* FunctionDeclaration */)); case 75 /* ClassKeyword */: - return parseClassDeclaration(createNodeWithJSDoc(235 /* ClassDeclaration */)); + return parseClassDeclaration(createNodeWithJSDoc(238 /* ClassDeclaration */)); case 90 /* IfKeyword */: return parseIfStatement(); case 81 /* DoKeyword */: @@ -19629,9 +19984,9 @@ var ts; case 88 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(223 /* ContinueStatement */); + return parseBreakOrContinueStatement(226 /* ContinueStatement */); case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(224 /* BreakStatement */); + return parseBreakOrContinueStatement(227 /* BreakStatement */); case 96 /* ReturnKeyword */: return parseReturnStatement(); case 107 /* WithKeyword */: @@ -19728,7 +20083,7 @@ var ts; if (node.decorators || node.modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var missing = createMissingNode(253 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(256 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; @@ -19751,16 +20106,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token() === 26 /* CommaToken */) { - return createNode(206 /* OmittedExpression */); + return createNode(208 /* OmittedExpression */); } - var node = createNode(182 /* BindingElement */); + var node = createNode(184 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(182 /* BindingElement */); + var node = createNode(184 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -19776,14 +20131,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(180 /* ObjectBindingPattern */); + var node = createNode(182 /* ObjectBindingPattern */); parseExpected(17 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(18 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(181 /* ArrayBindingPattern */); + var node = createNode(183 /* ArrayBindingPattern */); parseExpected(21 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(22 /* CloseBracketToken */); @@ -19805,7 +20160,7 @@ var ts; return parseVariableDeclaration(/*allowExclamation*/ true); } function parseVariableDeclaration(allowExclamation) { - var node = createNode(232 /* VariableDeclaration */); + var node = createNode(235 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); if (allowExclamation && node.name.kind === 71 /* Identifier */ && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { @@ -19818,7 +20173,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(233 /* VariableDeclarationList */); + var node = createNode(236 /* VariableDeclarationList */); switch (token()) { case 104 /* VarKeyword */: break; @@ -19856,13 +20211,13 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; } function parseVariableStatement(node) { - node.kind = 214 /* VariableStatement */; + node.kind = 217 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return finishNode(node); } function parseFunctionDeclaration(node) { - node.kind = 234 /* FunctionDeclaration */; + node.kind = 237 /* FunctionDeclaration */; parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); @@ -20044,7 +20399,7 @@ var ts; } function parseClassElement() { if (token() === 25 /* SemicolonToken */) { - var result = createNode(212 /* SemicolonClassElement */); + var result = createNode(215 /* SemicolonClassElement */); nextToken(); return finishNode(result); } @@ -20081,10 +20436,10 @@ var ts; return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 205 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 207 /* ClassExpression */); } function parseClassDeclaration(node) { - return parseClassDeclarationOrExpression(node, 235 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(node, 238 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(node, kind) { node.kind = kind; @@ -20120,28 +20475,28 @@ var ts; // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } if (isHeritageClause()) { - return parseList(21 /* HeritageClauses */, parseHeritageClause); + return parseList(22 /* HeritageClauses */, parseHeritageClause); } return undefined; } function parseHeritageClause() { var tok = token(); ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. - var node = createNode(268 /* HeritageClause */); + var node = createNode(271 /* HeritageClause */); node.token = tok; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); } function parseExpressionWithTypeArguments() { - var node = createNode(207 /* ExpressionWithTypeArguments */); + var node = createNode(209 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); node.typeArguments = tryParseTypeArguments(); return finishNode(node); } function tryParseTypeArguments() { return token() === 27 /* LessThanToken */ - ? parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) : undefined; } function isHeritageClause() { @@ -20151,7 +20506,7 @@ var ts; return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(node) { - node.kind = 236 /* InterfaceDeclaration */; + node.kind = 239 /* InterfaceDeclaration */; parseExpected(109 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -20160,7 +20515,7 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(node) { - node.kind = 237 /* TypeAliasDeclaration */; + node.kind = 240 /* TypeAliasDeclaration */; parseExpected(139 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -20174,13 +20529,13 @@ var ts; // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNodeWithJSDoc(273 /* EnumMember */); + var node = createNodeWithJSDoc(276 /* EnumMember */); node.name = parsePropertyName(); node.initializer = allowInAnd(parseInitializer); return finishNode(node); } function parseEnumDeclaration(node) { - node.kind = 238 /* EnumDeclaration */; + node.kind = 241 /* EnumDeclaration */; parseExpected(83 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(17 /* OpenBraceToken */)) { @@ -20193,7 +20548,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(240 /* ModuleBlock */); + var node = createNode(243 /* ModuleBlock */); if (parseExpected(17 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(18 /* CloseBraceToken */); @@ -20204,7 +20559,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(node, flags) { - node.kind = 239 /* ModuleDeclaration */; + node.kind = 242 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; @@ -20216,7 +20571,7 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(node) { - node.kind = 239 /* ModuleDeclaration */; + node.kind = 242 /* ModuleDeclaration */; if (token() === 144 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); @@ -20262,7 +20617,7 @@ var ts; return nextToken() === 41 /* SlashToken */; } function parseNamespaceExportDeclaration(node) { - node.kind = 242 /* NamespaceExportDeclaration */; + node.kind = 245 /* NamespaceExportDeclaration */; parseExpected(118 /* AsKeyword */); parseExpected(130 /* NamespaceKeyword */); node.name = parseIdentifier(); @@ -20280,7 +20635,7 @@ var ts; } } // Import statement - node.kind = 244 /* ImportDeclaration */; + node.kind = 247 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; @@ -20295,7 +20650,7 @@ var ts; return finishNode(node); } function parseImportEqualsDeclaration(node, identifier) { - node.kind = 243 /* ImportEqualsDeclaration */; + node.kind = 246 /* ImportEqualsDeclaration */; node.name = identifier; parseExpected(58 /* EqualsToken */); node.moduleReference = parseModuleReference(); @@ -20309,7 +20664,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(245 /* ImportClause */, fullStart); + var importClause = createNode(248 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -20319,7 +20674,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(247 /* NamedImports */); + importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(250 /* NamedImports */); } return finishNode(importClause); } @@ -20329,7 +20684,7 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(254 /* ExternalModuleReference */); + var node = createNode(257 /* ExternalModuleReference */); parseExpected(133 /* RequireKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = parseModuleSpecifier(); @@ -20352,7 +20707,7 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(246 /* NamespaceImport */); + var namespaceImport = createNode(249 /* NamespaceImport */); parseExpected(39 /* AsteriskToken */); parseExpected(118 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -20367,14 +20722,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 247 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(252 /* ExportSpecifier */); + return parseImportOrExportSpecifier(255 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(248 /* ImportSpecifier */); + return parseImportOrExportSpecifier(251 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -20399,19 +20754,19 @@ var ts; else { node.name = identifierName; } - if (kind === 248 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 251 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(node) { - node.kind = 250 /* ExportDeclaration */; + node.kind = 253 /* ExportDeclaration */; if (parseOptional(39 /* AsteriskToken */)) { parseExpected(143 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(251 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(254 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. @@ -20424,7 +20779,7 @@ var ts; return finishNode(node); } function parseExportAssignment(node) { - node.kind = 249 /* ExportAssignment */; + node.kind = 252 /* ExportAssignment */; if (parseOptional(58 /* EqualsToken */)) { node.isExportEquals = true; } @@ -20444,10 +20799,10 @@ var ts; } function isAnExternalModuleIndicatorNode(node) { return ts.hasModifier(node, 1 /* Export */) - || node.kind === 243 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 254 /* ExternalModuleReference */ - || node.kind === 244 /* ImportDeclaration */ - || node.kind === 249 /* ExportAssignment */ - || node.kind === 250 /* ExportDeclaration */ + || node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */ + || node.kind === 247 /* ImportDeclaration */ + || node.kind === 252 /* ExportAssignment */ + || node.kind === 253 /* ExportDeclaration */ ? node : undefined; } @@ -20481,13 +20836,14 @@ var ts; ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; - ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; // Number of parsing contexts + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -20510,7 +20866,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(278 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -20570,17 +20926,16 @@ var ts; ts.Debug.assert(start >= 0); ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); + // Check for /** (JSDoc opening part) + if (!isJSDocLikeText(content, start)) { + return undefined; + } var tags; var tagsPos; var tagsEnd; var comments = []; - var result; - // Check for /** (JSDoc opening part) - if (!isJSDocLikeText(content, start)) { - return result; - } // + 3 for leading /**, - 5 in total for /** */ - scanner.scanRange(start + 3, length - 5, function () { + return scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. var state = 1 /* SawAsterisk */; @@ -20605,7 +20960,7 @@ var ts; switch (token()) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -20665,22 +21020,21 @@ var ts; nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - result = createJSDocComment(); + removeTrailingWhitespace(comments); + return createJSDocComment(); }); - return result; function removeLeadingNewlines(comments) { while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { comments.shift(); } } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { comments.pop(); } } function createJSDocComment() { - var result = createNode(286 /* JSDocComment */, start); + var result = createNode(289 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -20707,13 +21061,30 @@ var ts; nextJSDocToken(); } } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 39 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } function parseTag(indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": @@ -20724,6 +21095,12 @@ var ts; case "constructor": tag = parseClassTag(atToken, tagName); break; + case "this": + tag = parseThisTag(atToken, tagName); + break; + case "enum": + tag = parseEnumTag(atToken, tagName); + break; case "arg": case "argument": case "param": @@ -20794,6 +21171,16 @@ var ts; indent += whitespace.length; } break; + case 17 /* OpenBraceToken */: + state = 2 /* SavingComments */; + if (lookAhead(function () { return nextJSDocToken() === 57 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + pushComment(scanner.getTokenText()); + nextJSDocToken(); + pushComment(scanner.getTokenText()); + nextJSDocToken(); + } + pushComment(scanner.getTokenText()); + break; case 39 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token @@ -20811,11 +21198,11 @@ var ts; tok = nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { - var result = createNode(289 /* JSDocTag */, atToken.pos); + var result = createNode(292 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); @@ -20834,7 +21221,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespace(); + skipWhitespaceOrAsterisk(); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -20868,15 +21255,15 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespace(); + skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(298 /* JSDocPropertyTag */, atToken.pos) : - createNode(293 /* JSDocParameterTag */, atToken.pos); + createNode(303 /* JSDocPropertyTag */, atToken.pos) : + createNode(297 /* JSDocParameterTag */, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -20896,18 +21283,18 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name, target) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(278 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 293 /* JSDocParameterTag */ || child.kind === 298 /* JSDocPropertyTag */) { + if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(287 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; if (typeExpression.type.kind === 167 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; @@ -20918,27 +21305,27 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 294 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(294 /* JSDocReturnTag */, atToken.pos); + var result = createNode(298 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 295 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(295 /* JSDocTypeTag */, atToken.pos); + var result = createNode(300 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var result = createNode(290 /* JSDocAugmentsTag */, atToken.pos); + var result = createNode(293 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); @@ -20946,7 +21333,7 @@ var ts; } function parseExpressionWithTypeArgumentsForAugments() { var usedBrace = parseOptional(17 /* OpenBraceToken */); - var node = createNode(207 /* ExpressionWithTypeArguments */); + var node = createNode(209 /* ExpressionWithTypeArguments */); node.expression = parsePropertyAccessEntityNameExpression(); node.typeArguments = tryParseTypeArguments(); var res = finishNode(node); @@ -20958,7 +21345,7 @@ var ts; function parsePropertyAccessEntityNameExpression() { var node = parseJSDocIdentifierName(); while (parseOptional(23 /* DotToken */)) { - var prop = createNode(185 /* PropertyAccessExpression */, node.pos); + var prop = createNode(187 /* PropertyAccessExpression */, node.pos); prop.expression = node; prop.name = parseJSDocIdentifierName(); node = finishNode(prop); @@ -20966,15 +21353,31 @@ var ts; return node; } function parseClassTag(atToken, tagName) { - var tag = createNode(291 /* JSDocClassTag */, atToken.pos); + var tag = createNode(294 /* JSDocClassTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + return finishNode(tag); + } + function parseThisTag(atToken, tagName) { + var tag = createNode(299 /* JSDocThisTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(atToken, tagName) { + var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); return finishNode(tag); } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(297 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); @@ -20987,12 +21390,12 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = scanner.getStartPos(); + var start_3 = atToken.pos; while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(287 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 295 /* JSDocTypeTag */) { + if (child.kind === 300 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21024,7 +21427,7 @@ var ts; } var typeNameOrNamespaceName = parseJSDocIdentifierName(); if (parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(239 /* ModuleDeclaration */, pos); + var jsDocNamespaceNode = createNode(242 /* ModuleDeclaration */, pos); if (nested) { jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } @@ -21038,7 +21441,7 @@ var ts; return typeNameOrNamespaceName; } function parseCallbackTag(atToken, tagName, indent) { - var callbackTag = createNode(292 /* JSDocCallbackTag */, atToken.pos); + var callbackTag = createNode(295 /* JSDocCallbackTag */, atToken.pos); callbackTag.atToken = atToken; callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); @@ -21047,7 +21450,7 @@ var ts; callbackTag.comment = parseTagComments(indent); var child; var start = scanner.getStartPos(); - var jsdocSignature = createNode(288 /* JSDocSignature */, start); + var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); @@ -21055,7 +21458,7 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(57 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 294 /* JSDocReturnTag */) { + if (tag && tag.kind === 298 /* JSDocReturnTag */) { return tag; } } @@ -21100,9 +21503,9 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 293 /* JSDocParameterTag */ && + if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && - (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { // TODO: GH#18217 + name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } return child; @@ -21169,16 +21572,14 @@ var ts; skipWhitespace(); var typeParameter = createNode(148 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); - skipWhitespace(); finishNode(typeParameter); + skipWhitespace(); typeParameters.push(typeParameter); } while (parseOptionalJsdoc(26 /* CommaToken */)); - if (constraint) { - ts.first(typeParameters).constraint = constraint.type; - } - var result = createNode(296 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; + result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); return result; @@ -21334,8 +21735,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { - var node = array_1[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -21485,8 +21886,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var node = array_2[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -21704,9 +22105,11 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + ts.isDeclarationFileName = isDeclarationFileName; /*@internal*/ function processCommentPragmas(context, sourceText) { var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); @@ -21980,6 +22383,7 @@ var ts; ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -22249,13 +22653,15 @@ var ts; { name: "noImplicitAny", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type }, { name: "strictNullChecks", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks @@ -22263,6 +22669,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types @@ -22270,6 +22677,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes @@ -22277,6 +22685,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, @@ -22284,6 +22693,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file @@ -22292,6 +22702,7 @@ var ts; { name: "noUnusedLocals", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_locals, @@ -22299,6 +22710,7 @@ var ts; { name: "noUnusedParameters", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_parameters, @@ -22306,6 +22718,7 @@ var ts; { name: "noImplicitReturns", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value @@ -22313,6 +22726,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement @@ -22383,12 +22797,14 @@ var ts; { name: "allowSyntheticDefaultImports", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, { name: "esModuleInterop", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports @@ -22403,7 +22819,6 @@ var ts; { name: "sourceRoot", type: "string", - isFilePath: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Source_Map_Options, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, @@ -22411,7 +22826,6 @@ var ts; { name: "mapRoot", type: "string", - isFilePath: true, paramType: ts.Diagnostics.LOCATION, category: ts.Diagnostics.Source_Map_Options, description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, @@ -22566,6 +22980,7 @@ var ts; { name: "noImplicitUseStrict", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output }, @@ -22604,24 +23019,28 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels }, { name: "allowUnreachableCode", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code }, { name: "suppressExcessPropertyErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, }, { name: "suppressImplicitAnyIndexErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, @@ -22640,6 +23059,7 @@ var ts; { name: "noStrictGenericChecks", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, }, @@ -23151,7 +23571,7 @@ var ts; var result = returnValue ? {} : undefined; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 270 /* PropertyAssignment */) { + if (element.kind !== 273 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); continue; } @@ -23161,9 +23581,10 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); - var option = knownOptions ? knownOptions.get(keyText) : undefined; - if (extraKeyDiagnosticMessage && !option) { + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); @@ -23228,13 +23649,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return Number(valueExpression.text); - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return -Number(valueExpression.operand.text); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -23251,7 +23672,7 @@ var ts; return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); } - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } @@ -24238,9 +24659,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -24469,9 +24890,7 @@ var ts; return perFolderCache; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; // TODO: GH#18217 - } + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { perModuleNameCache = createPerModuleNameCache(); @@ -24503,41 +24922,45 @@ var ts; return; } directoryPathMap.set(path, result); - var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); // find common prefix between directory and resolved file name - // this common prefix should be the shorted path that has the same resolution + // this common prefix should be the shortest path that has the same resolution // directory: /a/b/c/d/e // resolvedFileName: /a/b/foo.d.ts - var commonPrefix = getCommonPrefix(path, resolvedFileName); + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); var current = path; - while (true) { + while (current !== commonPrefix) { var parent = ts.getDirectoryPath(current); if (parent === current || directoryPathMap.has(parent)) { break; } directoryPathMap.set(parent, result); current = parent; - if (current === commonPrefix) { - break; - } } } function getCommonPrefix(directory, resolution) { - if (resolution === undefined) { - return undefined; - } var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); // find first position where directory and resolution differs var i = 0; - while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { i++; } - // find last directory separator before position i - var sep = directory.lastIndexOf(ts.directorySeparator, i); - if (sep < 0) { + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { + return undefined; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { return undefined; } - return directory.substr(0, sep); + return directory.substr(0, Math.max(sep, rootLength)); } } } @@ -24586,10 +25009,9 @@ var ts; } if (perFolderCache) { perFolderCache.set(moduleName, result); - // put result in per-module name cache - var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); - if (perModuleNameCache) { - perModuleNameCache.set(containingDirectory, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); } } } @@ -24814,15 +25236,15 @@ var ts; tryResolve(Extensions.JavaScript) || (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { @@ -24832,17 +25254,13 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - var originalPath = void 0; - if (!compilerOptions.preserveSymlinks && resolvedValue) { - originalPath = resolvedValue.path; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - if (path === originalPath) { - originalPath = undefined; - } - resolvedValue = __assign({}, resolvedValue, { path: path }); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -24895,7 +25313,8 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } - var nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -24909,11 +25328,11 @@ var ts; */ function parseNodeModuleFromPath(resolved) { var path = ts.normalizePath(resolved.path); - var idx = path.lastIndexOf(nodeModulesPathPart); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; } - var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); @@ -25256,7 +25675,7 @@ var ts; trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -25266,17 +25685,17 @@ var ts; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*originalPath*/ undefined, /*isExternalLibraryImport*/ false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -25311,7 +25730,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*originalPath*/ undefined, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -25322,20 +25741,6 @@ var ts; return value !== undefined ? { value: value } : undefined; } })(ts || (ts = {})); -//# sourceMappingURL=parser.js.map -"use strict"; -var __assign = (this && this.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; -}; -var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; /* @internal */ var ts; (function (ts) { @@ -25353,24 +25758,24 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 238 /* EnumDeclaration */: - if (ts.isConst(node)) { + case 241 /* EnumDeclaration */: + if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 244 /* ImportDeclaration */: - case 243 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: if (!(ts.hasModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. other uninstantiated module declarations. - case 240 /* ModuleBlock */: { + case 243 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateWorker(n); @@ -25392,7 +25797,7 @@ var ts; }); return state_1; } - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return getModuleInstanceState(node); case 71 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should @@ -25533,10 +25938,10 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; symbol.declarations = ts.append(symbol.declarations, node); - if (symbolFlags & 1955 /* HasExports */ && !symbol.exports) { + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } - if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } if (symbolFlags & 67216319 /* Value */) { @@ -25551,7 +25956,7 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.kind === 249 /* ExportAssignment */) { + if (node.kind === 252 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -25563,7 +25968,7 @@ var ts; if (name.kind === 147 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression)) { + if (ts.isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -25576,39 +25981,39 @@ var ts; return "__constructor" /* Constructor */; case 163 /* FunctionType */: case 158 /* CallSignature */: - case 288 /* JSDocSignature */: + case 291 /* JSDocSignature */: return "__call" /* Call */; case 164 /* ConstructorType */: case 159 /* ConstructSignature */: return "__new" /* New */; case 160 /* IndexSignature */: return "__index" /* Index */; - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 274 /* SourceFile */: + case 277 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 284 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); case 149 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 284 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 287 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); // TODO: GH#18217 + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); } /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @@ -25679,8 +26084,10 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; } if (symbol.declarations && symbol.declarations.length) { // If the current node is a default export of some sort, then check if @@ -25688,6 +26095,7 @@ var ts; // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } else { // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. @@ -25695,15 +26103,17 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 249 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } } } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); symbol = createSymbol(0 /* None */, name); } } @@ -25720,7 +26130,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 252 /* ExportSpecifier */ || (node.kind === 243 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 255 /* ExportSpecifier */ || (node.kind === 246 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -25787,7 +26197,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 193 /* ArrowFunction */) { + if (node.kind !== 195 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -25832,7 +26242,7 @@ var ts; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 274 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { node.flags |= emitFlags; } if (currentReturnTarget) { @@ -25881,8 +26291,8 @@ var ts; } } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 234 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 234 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -25896,8 +26306,8 @@ var ts; var savedSubtreeTransformFlags = subtreeTransformFlags; subtreeTransformFlags = 0 /* None */; var nodeArrayFlags = 0 /* None */; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; bindFunction(node); nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; } @@ -25914,77 +26324,78 @@ var ts; return; } switch (node.kind) { - case 219 /* WhileStatement */: + case 222 /* WhileStatement */: bindWhileStatement(node); break; - case 218 /* DoStatement */: + case 221 /* DoStatement */: bindDoStatement(node); break; - case 220 /* ForStatement */: + case 223 /* ForStatement */: bindForStatement(node); break; - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 217 /* IfStatement */: + case 220 /* IfStatement */: bindIfStatement(node); break; - case 225 /* ReturnStatement */: - case 229 /* ThrowStatement */: + case 228 /* ReturnStatement */: + case 232 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 224 /* BreakStatement */: - case 223 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 230 /* TryStatement */: + case 233 /* TryStatement */: bindTryStatement(node); break; - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: bindSwitchStatement(node); break; - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: bindCaseBlock(node); break; - case 266 /* CaseClause */: + case 269 /* CaseClause */: bindCaseClause(node); break; - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: bindLabeledStatement(node); break; - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: bindBinaryExpressionFlow(node); break; - case 194 /* DeleteExpression */: + case 196 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 187 /* CallExpression */: + case 189 /* CallExpression */: bindCallExpressionFlow(node); break; - case 297 /* JSDocTypedefTag */: - case 292 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 274 /* SourceFile */: + case 277 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; - case 213 /* Block */: - case 240 /* ModuleBlock */: + } + case 216 /* Block */: + case 243 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; default: @@ -25997,24 +26408,26 @@ var ts; switch (expr.kind) { case 71 /* Identifier */: case 99 /* ThisKeyword */: - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return isNarrowableReference(expr); - case 187 /* CallExpression */: + case 189 /* CallExpression */: return hasNarrowableArgument(expr); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); } return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || - expr.kind === 99 /* ThisKeyword */ || - expr.kind === 97 /* SuperKeyword */ || - expr.kind === 185 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -26025,7 +26438,7 @@ var ts; } } } - if (expr.expression.kind === 185 /* PropertyAccessExpression */ && + if (expr.expression.kind === 187 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26058,9 +26471,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: switch (expr.operatorToken.kind) { case 58 /* EqualsToken */: return isNarrowableOperand(expr.left); @@ -26138,33 +26551,33 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 217 /* IfStatement */: - case 219 /* WhileStatement */: - case 218 /* DoStatement */: + case 220 /* IfStatement */: + case 222 /* WhileStatement */: + case 221 /* DoStatement */: return parent.expression === node; - case 220 /* ForStatement */: - case 201 /* ConditionalExpression */: + case 223 /* ForStatement */: + case 203 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 191 /* ParenthesizedExpression */) { + if (node.kind === 193 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 198 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + else if (node.kind === 200 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 200 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || + return node.kind === 202 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 54 /* BarBarToken */); } } } function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 191 /* ParenthesizedExpression */ || - node.parent.kind === 198 /* PrefixUnaryExpression */ && + while (node.parent.kind === 193 /* ParenthesizedExpression */ || + node.parent.kind === 200 /* PrefixUnaryExpression */ && node.parent.operator === 51 /* ExclamationToken */) { node = node.parent; } @@ -26206,7 +26619,7 @@ var ts; } function bindDoStatement(node) { var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 228 /* LabeledStatement */ + var enclosingLabeledStatement = node.parent.kind === 231 /* LabeledStatement */ ? ts.lastOrUndefined(activeLabels) : undefined; // if do statement is wrapped in labeled statement then target labels for break/continue with or without @@ -26240,13 +26653,13 @@ var ts; var postLoopLabel = createBranchLabel(); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 222 /* ForOfStatement */) { + if (node.kind === 225 /* ForOfStatement */) { bind(node.awaitModifier); } bind(node.expression); addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 233 /* VariableDeclarationList */) { + if (node.initializer.kind !== 236 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -26268,7 +26681,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 225 /* ReturnStatement */) { + if (node.kind === 228 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -26288,7 +26701,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 224 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 227 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -26384,7 +26797,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 267 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; @@ -26450,16 +26863,16 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } - if (!node.statement || node.statement.kind !== 218 /* DoStatement */) { + if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { // do statement sets current flow inside bindDoStatement addAntecedent(postStatementLabel, currentFlow); currentFlow = finishFlowLabel(postStatementLabel); } } function bindDestructuringTargetFlow(node) { - if (node.kind === 200 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -26470,10 +26883,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowAssignment(currentFlow, node); } - else if (node.kind === 183 /* ArrayLiteralExpression */) { + else if (node.kind === 185 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 204 /* SpreadElement */) { + if (e.kind === 206 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -26481,16 +26894,16 @@ var ts; } } } - else if (node.kind === 184 /* ObjectLiteralExpression */) { + else if (node.kind === 186 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 270 /* PropertyAssignment */) { + if (p.kind === 273 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 271 /* ShorthandPropertyAssignment */) { + else if (p.kind === 274 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 272 /* SpreadAssignment */) { + else if (p.kind === 275 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -26546,7 +26959,7 @@ var ts; bindEachChild(node); if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 186 /* ElementAccessExpression */) { + if (operator === 58 /* EqualsToken */ && node.left.kind === 188 /* ElementAccessExpression */) { var elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -26557,7 +26970,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 185 /* PropertyAccessExpression */) { + if (node.expression.kind === 187 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -26604,10 +27017,10 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = node.expression; - while (expr.kind === 191 /* ParenthesizedExpression */) { + while (expr.kind === 193 /* ParenthesizedExpression */) { expr = expr.expression; } - if (expr.kind === 192 /* FunctionExpression */ || expr.kind === 193 /* ArrowFunction */) { + if (expr.kind === 194 /* FunctionExpression */ || expr.kind === 195 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -26615,7 +27028,7 @@ var ts; else { bindEachChild(node); } - if (node.expression.kind === 185 /* PropertyAccessExpression */) { + if (node.expression.kind === 187 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); @@ -26624,21 +27037,21 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 205 /* ClassExpression */: - case 235 /* ClassDeclaration */: - case 238 /* EnumDeclaration */: - case 184 /* ObjectLiteralExpression */: + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 186 /* ObjectLiteralExpression */: case 166 /* TypeLiteral */: - case 287 /* JSDocTypeLiteral */: - case 263 /* JsxAttributes */: + case 290 /* JSDocTypeLiteral */: + case 266 /* JsxAttributes */: return 1 /* IsContainer */; - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 239 /* ModuleDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 177 /* MappedType */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 179 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 274 /* SourceFile */: + case 277 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; case 154 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { @@ -26646,32 +27059,32 @@ var ts; } // falls through case 155 /* Constructor */: - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: case 153 /* MethodSignature */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: case 158 /* CallSignature */: - case 288 /* JSDocSignature */: - case 284 /* JSDocFunctionType */: + case 291 /* JSDocSignature */: + case 287 /* JSDocFunctionType */: case 163 /* FunctionType */: case 159 /* ConstructSignature */: case 160 /* IndexSignature */: case 164 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; case 152 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 269 /* CatchClause */: - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 241 /* CaseBlock */: + case 272 /* CatchClause */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 244 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 213 /* Block */: + case 216 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -26704,20 +27117,20 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 274 /* SourceFile */: + case 277 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 205 /* ClassExpression */: - case 235 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 166 /* TypeLiteral */: - case 287 /* JSDocTypeLiteral */: - case 184 /* ObjectLiteralExpression */: - case 236 /* InterfaceDeclaration */: - case 263 /* JsxAttributes */: + case 290 /* JSDocTypeLiteral */: + case 186 /* ObjectLiteralExpression */: + case 239 /* InterfaceDeclaration */: + case 266 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the @@ -26728,21 +27141,21 @@ var ts; case 164 /* ConstructorType */: case 158 /* CallSignature */: case 159 /* ConstructSignature */: - case 288 /* JSDocSignature */: + case 291 /* JSDocSignature */: case 160 /* IndexSignature */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: - case 284 /* JSDocFunctionType */: - case 297 /* JSDocTypedefTag */: - case 292 /* JSDocCallbackTag */: - case 237 /* TypeAliasDeclaration */: - case 177 /* MappedType */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 287 /* JSDocFunctionType */: + case 302 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 240 /* TypeAliasDeclaration */: + case 179 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -26763,11 +27176,11 @@ var ts; : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 274 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 274 /* SourceFile */ || body.kind === 240 /* ModuleBlock */)) { + var body = node.kind === 277 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 277 /* SourceFile */ || body.kind === 243 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 250 /* ExportDeclaration */ || stat.kind === 249 /* ExportAssignment */) { + if (stat.kind === 253 /* ExportDeclaration */ || stat.kind === 252 /* ExportAssignment */) { return true; } } @@ -26851,7 +27264,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 272 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + if (prop.kind === 275 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { continue; } var identifier = prop.name; @@ -26863,7 +27276,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 270 /* PropertyAssignment */ || prop.kind === 271 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */ + var currentKind = prop.kind === 273 /* PropertyAssignment */ || prop.kind === 274 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -26895,10 +27308,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 274 /* SourceFile */: + case 277 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -27039,8 +27452,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 274 /* SourceFile */ && - blockScopeContainer.kind !== 239 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 277 /* SourceFile */ && + blockScopeContainer.kind !== 242 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -27077,13 +27490,26 @@ var ts; errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } - function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); if (isError) { file.bindDiagnostics.push(diag); } @@ -27136,7 +27562,11 @@ var ts; } else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + var saveParent = parent; + if (node.kind === 1 /* EndOfFileToken */) + parent = node; bindJSDoc(node); + parent = saveParent; } inStrictMode = saveInStrictMode; } @@ -27194,19 +27624,26 @@ var ts; } // falls through case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 271 /* ShorthandPropertyAssignment */)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 274 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkStrictModeIdentifier(node); - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } + if (ts.isInJavaScriptFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(container, "module")) { + declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + } break; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: var specialKind = ts.getSpecialPropertyAssignmentKind(node); switch (specialKind) { case 1 /* ExportsProperty */: @@ -27234,19 +27671,21 @@ var ts; ts.Debug.fail("Unknown special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return checkStrictModeCatchClause(node); - case 194 /* DeleteExpression */: + case 196 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 226 /* WithStatement */: + case 229 /* WithStatement */: return checkStrictModeWithStatement(node); - case 174 /* ThisType */: + case 231 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); + case 176 /* ThisType */: seenThisKeyword = true; return; case 161 /* TypePredicate */: @@ -27255,18 +27694,18 @@ var ts; return bindTypeParameter(node); case 149 /* Parameter */: return bindParameter(node); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 182 /* BindingElement */: + case 184 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: return bindPropertyWorker(node); - case 270 /* PropertyAssignment */: - case 271 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 273 /* EnumMember */: + case 276 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); case 158 /* CallSignature */: case 159 /* ConstructSignature */: @@ -27279,7 +27718,7 @@ var ts; // so that it will conflict with any other object literal members with the same // name. return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); @@ -27288,83 +27727,83 @@ var ts; case 157 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); case 163 /* FunctionType */: - case 284 /* JSDocFunctionType */: - case 288 /* JSDocSignature */: + case 287 /* JSDocFunctionType */: + case 291 /* JSDocSignature */: case 164 /* ConstructorType */: return bindFunctionOrConstructorType(node); case 166 /* TypeLiteral */: - case 287 /* JSDocTypeLiteral */: - case 177 /* MappedType */: + case 290 /* JSDocTypeLiteral */: + case 179 /* MappedType */: return bindAnonymousTypeWorker(node); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return bindFunctionExpression(node); - case 187 /* CallExpression */: + case 189 /* CallExpression */: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 205 /* ClassExpression */: - case 235 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 263 /* JsxAttributes */: + case 266 /* JsxAttributes */: return bindJsxAttributes(node); - case 262 /* JsxAttribute */: + case 265 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 243 /* ImportEqualsDeclaration */: - case 246 /* NamespaceImport */: - case 248 /* ImportSpecifier */: - case 252 /* ExportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 242 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 245 /* ImportClause */: + case 248 /* ImportClause */: return bindImportClause(node); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return bindExportDeclaration(node); - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return bindExportAssignment(node); - case 274 /* SourceFile */: + case 277 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 213 /* Block */: + case 216 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 293 /* JSDocParameterTag */: - if (node.parent.kind === 288 /* JSDocSignature */) { + case 297 /* JSDocParameterTag */: + if (node.parent.kind === 291 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 287 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 290 /* JSDocTypeLiteral */) { break; } // falls through - case 298 /* JSDocPropertyTag */: + case 303 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 283 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 297 /* JSDocTypedefTag */: - case 292 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -27396,7 +27835,7 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 249 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value @@ -27410,7 +27849,7 @@ var ts; if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 274 /* SourceFile */) { + if (node.parent.kind !== 277 /* SourceFile */) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); return; } @@ -27444,17 +27883,21 @@ var ts; } } function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator) { + return false; + } if (!file.commonJsModuleIndicator) { file.commonJsModuleIndicator = node; - if (!file.externalModuleIndicator) { - bindSourceFileAsExternalModule(); - } + bindSourceFileAsExternalModule(); } + return true; } function bindExportsPropertyAssignment(node) { // When we create a property via 'exports.foo = bar', the 'exports.foo' property access // expression is the declaration - setCommonJsModuleIndicator(node); + if (!setCommonJsModuleIndicator(node)) { + return; + } var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { @@ -27474,14 +27917,14 @@ var ts; // is still pointing to 'module.exports'. // We do not want to consider this as 'export=' since a module can have only one of these. // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + if (!setCommonJsModuleIndicator(node)) { + return; + } var assignedExpression = ts.getRightMostAssignedExpression(node.right); if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { - // Mark it as a module in case there are no other exports in the file - setCommonJsModuleIndicator(node); return; } // 'module.exports = expr' assignment - setCommonJsModuleIndicator(node); var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; @@ -27491,8 +27934,8 @@ var ts; ts.Debug.assert(ts.isInJavaScriptFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { @@ -27519,7 +27962,7 @@ var ts; var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; - case 274 /* SourceFile */: + case 277 /* SourceFile */: // this.foo assignment in a source file // Do not bind. It would be nice to support this someday though. break; @@ -27531,7 +27974,7 @@ var ts; if (node.expression.kind === 99 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 274 /* SourceFile */) { + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -27564,6 +28007,11 @@ var ts; } function bindSpecialPropertyAssignment(node) { var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } // Fix up parent pointers since we're going to use these nodes before we bind into them node.left.parent = node; node.right.parent = node; @@ -27588,9 +28036,9 @@ var ts; function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 274 /* SourceFile */ && + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) - : propertyAccess.parent.parent.kind === 274 /* SourceFile */; + : propertyAccess.parent.parent.kind === 277 /* SourceFile */; if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { // make symbols or add declarations for intermediate containers var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; @@ -27639,6 +28087,7 @@ var ts; ts.isBinaryExpression(node) ? node.right : ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right : undefined; + init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); @@ -27683,7 +28132,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 235 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); } else { @@ -27716,7 +28165,7 @@ var ts; prototypeSymbol.parent = symbol; } function bindEnumDeclaration(node) { - return ts.isConst(node) + return ts.isEnumConst(node) ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); } @@ -27746,7 +28195,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 293 /* JSDocParameterTag */ && container.kind !== 288 /* JSDocSignature */) { + if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -27823,7 +28272,7 @@ var ts; declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 172 /* InferType */) { + else if (node.parent.kind === 174 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { @@ -27851,13 +28300,13 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 215 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 218 /* EmptyStatement */) || // report error on class declarations - node.kind === 235 /* ClassDeclaration */ || + node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 239 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 238 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -27870,18 +28319,48 @@ var ts; // - node is not block scoped variable statement and at least one variable declaration has initializer // Rationale: we don't want to report errors on non-initialized var's since they are hoisted // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var isError = ts.unreachableCodeIsError(options) && + var isError_1 = ts.unreachableCodeIsError(options) && !(node.flags & 4194304 /* Ambient */) && (!ts.isVariableStatement(node) || !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || node.declarationList.declarations.some(function (d) { return !!d.initializer; })); - errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); } } } return true; } } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return true; + case 242 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 241 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || @@ -27914,43 +28393,43 @@ var ts; function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { - case 187 /* CallExpression */: + case 189 /* CallExpression */: return computeCallExpression(node, subtreeFlags); - case 188 /* NewExpression */: + case 190 /* NewExpression */: return computeNewExpression(node, subtreeFlags); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return computeModuleDeclaration(node, subtreeFlags); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return computeParenthesizedExpression(node, subtreeFlags); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return computeBinaryExpression(node, subtreeFlags); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return computeExpressionStatement(node, subtreeFlags); case 149 /* Parameter */: return computeParameter(node, subtreeFlags); - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: return computeArrowFunction(node, subtreeFlags); - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: return computeFunctionExpression(node, subtreeFlags); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return computeFunctionDeclaration(node, subtreeFlags); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return computeVariableDeclaration(node, subtreeFlags); - case 233 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return computeVariableDeclarationList(node, subtreeFlags); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return computeVariableStatement(node, subtreeFlags); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return computeLabeledStatement(node, subtreeFlags); - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return computeClassDeclaration(node, subtreeFlags); - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: return computeClassExpression(node, subtreeFlags); - case 268 /* HeritageClause */: + case 271 /* HeritageClause */: return computeHeritageClause(node, subtreeFlags); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return computeCatchClause(node, subtreeFlags); - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return computeExpressionWithTypeArguments(node, subtreeFlags); case 155 /* Constructor */: return computeConstructor(node, subtreeFlags); @@ -27961,11 +28440,11 @@ var ts; case 156 /* GetAccessor */: case 157 /* SetAccessor */: return computeAccessor(node, subtreeFlags); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return computeImportEquals(node, subtreeFlags); - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); @@ -28017,12 +28496,12 @@ var ts; var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 184 /* ObjectLiteralExpression */) { + if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 186 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ESNext if they contain rest transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 183 /* ArrayLiteralExpression */) { + else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 185 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; } @@ -28071,8 +28550,8 @@ var ts; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. - if (expressionKind === 208 /* AsExpression */ - || expressionKind === 190 /* TypeAssertionExpression */) { + if (expressionKind === 210 /* AsExpression */ + || expressionKind === 192 /* TypeAssertionExpression */) { transformFlags |= 3 /* AssertTypeScript */; } // If the expression of a ParenthesizedExpression is a destructuring assignment, @@ -28449,13 +28928,13 @@ var ts; var excludeFlags = 939525441 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: - case 197 /* AwaitExpression */: + case 199 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; - case 190 /* TypeAssertionExpression */: - case 208 /* AsExpression */: - case 301 /* PartiallyEmittedExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: + case 306 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; @@ -28466,25 +28945,25 @@ var ts; case 117 /* AbstractKeyword */: case 124 /* DeclareKeyword */: case 76 /* ConstKeyword */: - case 238 /* EnumDeclaration */: - case 273 /* EnumMember */: - case 209 /* NonNullExpression */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 211 /* NonNullExpression */: case 132 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; break; - case 255 /* JsxElement */: - case 256 /* JsxSelfClosingElement */: - case 257 /* JsxOpeningElement */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: case 10 /* JsxText */: - case 258 /* JsxClosingElement */: - case 259 /* JsxFragment */: - case 260 /* JsxOpeningFragment */: - case 261 /* JsxClosingFragment */: - case 262 /* JsxAttribute */: - case 263 /* JsxAttributes */: - case 264 /* JsxSpreadAttribute */: - case 265 /* JsxExpression */: + case 261 /* JsxClosingElement */: + case 262 /* JsxFragment */: + case 263 /* JsxOpeningFragment */: + case 264 /* JsxClosingFragment */: + case 265 /* JsxAttribute */: + case 266 /* JsxAttributes */: + case 267 /* JsxSpreadAttribute */: + case 268 /* JsxExpression */: // These nodes are Jsx syntax. transformFlags |= 4 /* AssertJsx */; break; @@ -28492,11 +28971,11 @@ var ts; case 14 /* TemplateHead */: case 15 /* TemplateMiddle */: case 16 /* TemplateTail */: - case 202 /* TemplateExpression */: - case 189 /* TaggedTemplateExpression */: - case 271 /* ShorthandPropertyAssignment */: + case 204 /* TemplateExpression */: + case 191 /* TaggedTemplateExpression */: + case 274 /* ShorthandPropertyAssignment */: case 115 /* StaticKeyword */: - case 210 /* MetaProperty */: + case 212 /* MetaProperty */: // These nodes are ES6 syntax. transformFlags |= 192 /* AssertES2015 */; break; @@ -28510,14 +28989,14 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } break; - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { transformFlags |= 8 /* AssertESNext */; } transformFlags |= 192 /* AssertES2015 */; break; - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; @@ -28544,19 +29023,21 @@ var ts; case 166 /* TypeLiteral */: case 167 /* ArrayType */: case 168 /* TupleType */: - case 169 /* UnionType */: - case 170 /* IntersectionType */: - case 171 /* ConditionalType */: - case 172 /* InferType */: - case 173 /* ParenthesizedType */: - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 174 /* ThisType */: - case 175 /* TypeOperator */: - case 176 /* IndexedAccessType */: - case 177 /* MappedType */: - case 178 /* LiteralType */: - case 242 /* NamespaceExportDeclaration */: + case 169 /* OptionalType */: + case 170 /* RestType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 173 /* ConditionalType */: + case 174 /* InferType */: + case 175 /* ParenthesizedType */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 176 /* ThisType */: + case 177 /* TypeOperator */: + case 178 /* IndexedAccessType */: + case 179 /* MappedType */: + case 180 /* LiteralType */: + case 245 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. transformFlags = 3 /* AssertTypeScript */; excludeFlags = -3 /* TypeExcludes */; @@ -28578,10 +29059,10 @@ var ts; transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; } break; - case 204 /* SpreadElement */: + case 206 /* SpreadElement */: transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; break; - case 272 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; break; case 97 /* SuperKeyword */: @@ -28593,18 +29074,18 @@ var ts; // Mark this node and its ancestors as containing a lexical `this` keyword. transformFlags |= 16384 /* ContainsLexicalThis */; break; - case 180 /* ObjectBindingPattern */: + case 182 /* ObjectBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; if (subtreeFlags & 524288 /* ContainsRest */) { transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } excludeFlags = 940049729 /* BindingPatternExcludes */; break; - case 181 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; excludeFlags = 940049729 /* BindingPatternExcludes */; break; - case 182 /* BindingElement */: + case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { transformFlags |= 524288 /* ContainsRest */; @@ -28614,7 +29095,7 @@ var ts; // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: excludeFlags = 942740801 /* ObjectLiteralExcludes */; if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it @@ -28632,8 +29113,8 @@ var ts; transformFlags |= 8 /* AssertESNext */; } break; - case 183 /* ArrayLiteralExpression */: - case 188 /* NewExpression */: + case 185 /* ArrayLiteralExpression */: + case 190 /* NewExpression */: excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; if (subtreeFlags & 524288 /* ContainsSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 @@ -28641,26 +29122,26 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } break; - case 218 /* DoStatement */: - case 219 /* WhileStatement */: - case 220 /* ForStatement */: - case 221 /* ForInStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 274 /* SourceFile */: + case 277 /* SourceFile */: if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; - case 223 /* ContinueStatement */: - case 224 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; break; } @@ -28676,27 +29157,27 @@ var ts; */ /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 161 /* FirstTypeNode */ && kind <= 179 /* LastTypeNode */) { + if (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) { return -3 /* TypeExcludes */; } switch (kind) { - case 187 /* CallExpression */: - case 188 /* NewExpression */: - case 183 /* ArrayLiteralExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 185 /* ArrayLiteralExpression */: return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return 977327425 /* ModuleExcludes */; case 149 /* Parameter */: return 939525441 /* ParameterExcludes */; - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: return 1003902273 /* ArrowFunctionExcludes */; - case 192 /* FunctionExpression */: - case 234 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: return 1003935041 /* FunctionExcludes */; - case 233 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return 948962625 /* VariableDeclarationListExcludes */; - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return 942011713 /* ClassExcludes */; case 155 /* Constructor */: return 1003668801 /* ConstructorExcludes */; @@ -28718,24 +29199,24 @@ var ts; case 158 /* CallSignature */: case 159 /* ConstructSignature */: case 160 /* IndexSignature */: - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return 942740801 /* ObjectLiteralExcludes */; - case 269 /* CatchClause */: + case 272 /* CatchClause */: return 940574017 /* CatchClauseExcludes */; - case 180 /* ObjectBindingPattern */: - case 181 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: return 940049729 /* BindingPatternExcludes */; - case 190 /* TypeAssertionExpression */: - case 208 /* AsExpression */: - case 301 /* PartiallyEmittedExpression */: - case 191 /* ParenthesizedExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: + case 306 /* PartiallyEmittedExpression */: + case 193 /* ParenthesizedExpression */: case 97 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; - case 185 /* PropertyAccessExpression */: - case 186 /* ElementAccessExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return 671089985 /* PropertyAccessExcludes */; default: return 939525441 /* NodeExcludes */; @@ -28754,7 +29235,7 @@ var ts; /** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -28830,7 +29311,7 @@ var ts; ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { - visitType(getConstraintFromTypeParameter(type)); + visitType(getConstraintOfTypeParameter(type)); } function visitUnionOrIntersectionType(type) { ts.forEach(type.types, visitType); @@ -28902,7 +29383,7 @@ var ts; } var t = getTypeOfSymbol(symbol); visitType(t); // Should handle members on classes and such - if (symbol.flags & 1955 /* HasExports */) { + if (symbol.exports) { symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { @@ -28992,7 +29473,6 @@ var ts; undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); - var moduleSymbol = createSymbol(4 /* Property */, "module"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; // for public members that accept a Node or one of its subtypes, we must guard against @@ -29024,6 +29504,7 @@ var ts; getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, getIndexInfoOfType: getIndexInfoOfType, getSignaturesOfType: getSignaturesOfType, getIndexTypeOfType: getIndexTypeOfType, @@ -29035,6 +29516,7 @@ var ts; return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, getReturnTypeOfSignature: getReturnTypeOfSignature, getNullableType: getNullableType, getNonNullableType: getNonNullableType, @@ -29097,13 +29579,16 @@ var ts; writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); @@ -29114,12 +29599,11 @@ var ts; }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { - var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); - apparentArgumentCount = theArgumentCount; - var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; - apparentArgumentCount = undefined; - return res; + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); }, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); @@ -29156,7 +29640,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); @@ -29195,10 +29679,11 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, + isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentModule: function (node, target) { return getSuggestionForNonexistentModule(node, target); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -29217,6 +29702,9 @@ var ts; return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } var diagnostics; try { // Record the cancellation token so it can be checked later on during checkSourceElement. @@ -29236,8 +29724,8 @@ var ts; cancellationToken = undefined; } function addUnusedDiagnostics() { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { - if (!unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } }); @@ -29253,7 +29741,14 @@ var ts; } } }; - var tupleTypes = []; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } + var tupleTypes = ts.createMap(); var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); @@ -29308,8 +29803,8 @@ var ts; var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; /** @@ -29479,7 +29974,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -29523,143 +30018,6 @@ var ts; var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; - /** - * @deprecated - */ - function getSymbolDisplayBuilder() { - return { - buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { - typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); - }, - buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { - if (flags === void 0) { flags = 0 /* None */; } - symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); - }, - buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { - signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); - }, - buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { - var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildParameterDisplay: function (symbol, writer, enclosing, flags) { - var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 - }, - buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { - var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 - }, - buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { - typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); - }, - buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { - var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeList(26896 /* TypeParameters */, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { - var printer = ts.createPrinter({ removeComments: true }); - var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); - var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; // TODO: GH#18217 - var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); // TODO: GH#18217 - printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { - var printer = ts.createPrinter({ removeComments: true }); - var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); // TODO: GH#18217 - printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { - writer.writePunctuation(":"); - writer.writeSpace(" "); - var predicate = getTypePredicateOfSignature(signature); - if (predicate) { - return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); - } - var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); // TODO: GH#18217 - } - }; - function emitTextWriterWrapper(underlying) { - return { - write: ts.noop, - writeTextOfNode: ts.noop, - writeLine: ts.noop, - increaseIndent: function () { - return underlying.increaseIndent(); - }, - decreaseIndent: function () { - return underlying.decreaseIndent(); - }, - getText: function () { - return ""; - }, - rawWrite: ts.noop, - writeLiteral: function (s) { - return underlying.writeStringLiteral(s); - }, - getTextPos: function () { - return 0; - }, - getLine: function () { - return 0; - }, - getColumn: function () { - return 0; - }, - getIndent: function () { - return 0; - }, - isAtStartOfLine: function () { - return false; - }, - clear: function () { - return underlying.clear(); - }, - writeKeyword: function (text) { - return underlying.writeKeyword(text); - }, - writeOperator: function (text) { - return underlying.writeOperator(text); - }, - writePunctuation: function (text) { - return underlying.writePunctuation(text); - }, - writeSpace: function (text) { - return underlying.writeSpace(text); - }, - writeStringLiteral: function (text) { - return underlying.writeStringLiteral(text); - }, - writeParameter: function (text) { - return underlying.writeParameter(text); - }, - writeProperty: function (text) { - return underlying.writeProperty(text); - }, - writeSymbol: function (text, symbol) { - return underlying.writeSymbol(text, symbol); - }, - trackSymbol: function (symbol, enclosing, meaning) { - return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); - }, - reportInaccessibleThisError: function () { - return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); - }, - reportPrivateInBaseOfClassExpression: function (name) { - return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); - }, - reportInaccessibleUniqueSymbolError: function () { - return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); - } - }; - } - } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -29697,11 +30055,37 @@ var ts; getDiagnostics(sourceFile, cancellationToken); return emitResolver; } + function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + var existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } + else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function addRelatedInfo(diagnostic) { + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + var _a; + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } function error(location, message, arg0, arg1, arg2, arg3) { var diagnostic = location ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); diagnostics.add(diagnostic); + return diagnostic; } function addErrorOrSuggestion(isError, diagnostic) { if (isError) { @@ -29821,22 +30205,57 @@ var ts; error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { - var message_2 = target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */ + var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); + var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ + : isEitherBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - error(errorNode, message_2, symbolToString(source)); - }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - error(errorNode, message_2, symbolToString(source)); - }); + var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch + if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; + var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; + var cacheKey = firstFile_1.path + "|" + secondFile.path; + var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; + var symbolName_1 = symbolToString(source); + var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; + var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; + ts.forEach(source.declarations, function (node) { + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; + targetList.instances.push(errorNode); + }); + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; + targetList.instances.push(errorNode); + }); + existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); + existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); + amalgamatedDuplicates.set(cacheKey, existing); + return target; + } + var symbolName_2 = symbolToString(source); + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + }); + } + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + var err = lookupOrIssueError(errorNode, message, symbolName); + if (relatedNode && ts.length(err.relatedInformation) < 5) { + addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + } + } function combineSymbolTables(first, second) { if (!ts.hasEntries(first)) return second; @@ -29911,7 +30330,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 274 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -29969,17 +30388,17 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 182 /* BindingElement */) { + if (declaration.kind === 184 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 182 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 184 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 232 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235 /* VariableDeclaration */), usage); } - else if (declaration.kind === 232 /* VariableDeclaration */) { + else if (declaration.kind === 235 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -29997,22 +30416,23 @@ var ts; // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) // or if usage is in a type context: // 1. inside a type query (typeof in type position) - if (usage.parent.kind === 252 /* ExportSpecifier */ || (usage.parent.kind === 249 /* ExportAssignment */ && usage.parent.isExportEquals)) { + // 2. inside a jsdoc comment + if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 249 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 252 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 214 /* VariableStatement */: - case 220 /* ForStatement */: - case 222 /* ForOfStatement */: + case 217 /* VariableStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -30084,7 +30504,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 286 /* JSDocComment */) { + if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30104,7 +30524,7 @@ var ts; !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } - else if (location.kind === 171 /* ConditionalType */) { + else if (location.kind === 173 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -30118,14 +30538,14 @@ var ts; } } switch (location.kind) { - case 274 /* SourceFile */: + case 277 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 274 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -30149,7 +30569,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 252 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 255 /* ExportSpecifier */)) { break; } } @@ -30163,7 +30583,7 @@ var ts; } } break; - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } @@ -30186,9 +30606,9 @@ var ts; } } break; - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 236 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container @@ -30204,7 +30624,7 @@ var ts; } break loop; } - if (location.kind === 205 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 207 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -30212,7 +30632,7 @@ var ts; } } break; - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; @@ -30234,7 +30654,7 @@ var ts; // case 147 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 236 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -30247,14 +30667,14 @@ var ts; case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 234 /* FunctionDeclaration */: - case 193 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -30289,8 +30709,8 @@ var ts; location = location.parent; } break; - case 297 /* JSDocTypedefTag */: - case 292 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); break; @@ -30309,7 +30729,7 @@ var ts; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 274 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports") { return lastLocation.symbol; } @@ -30323,10 +30743,6 @@ var ts; if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } - if (ts.isIdentifier(originalLocation) && ts.isPropertyAccessExpression(originalLocation.parent) && - originalLocation.escapedText === "module" && originalLocation.parent.name.escapedText === "exports") { - return moduleSymbol; - } } } if (!result) { @@ -30339,9 +30755,13 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { - suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } } if (!suggestion) { @@ -30383,7 +30803,7 @@ var ts; // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 242 /* NamespaceExportDeclaration */) { + if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -30392,12 +30812,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 234 /* FunctionDeclaration */: - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 238 /* EnumDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 239 /* ModuleDeclaration */: // For `namespace N { N; }` + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 242 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -30465,9 +30885,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 71 /* Identifier */: - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -30531,18 +30951,26 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 238 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var diagnosticMessage = void 0; + var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration)); if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); } else if (result.flags & 256 /* RegularEnum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + else { + ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } } @@ -30555,13 +30983,13 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return node; - case 245 /* ImportClause */: + case 248 /* ImportClause */: return node.parent; - case 246 /* NamespaceImport */: + case 249 /* NamespaceImport */: return node.parent.parent; - case 248 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -30571,7 +30999,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 254 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -30686,7 +31114,7 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } } } @@ -30721,9 +31149,13 @@ var ts; if (!symbol) { var moduleName = getFullyQualifiedName(moduleSymbol); var declarationName = ts.declarationNameToString(name); - var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); @@ -30759,20 +31191,20 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 245 /* ImportClause */: + case 248 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 246 /* NamespaceImport */: + case 249 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 248 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 252 /* ExportSpecifier */: + case 255 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 249 /* ExportAssignment */: - case 200 /* BinaryExpression */: + case 252 /* ExportAssignment */: + case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 242 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -30833,11 +31265,11 @@ var ts; var node = getDeclarationOfAliasSymbol(symbol); if (!node) return ts.Debug.fail(); - if (node.kind === 249 /* ExportAssignment */) { + if (node.kind === 252 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 252 /* ExportSpecifier */) { + else if (node.kind === 255 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -30865,7 +31297,7 @@ var ts; else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 243 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -30889,7 +31321,7 @@ var ts; return symbolFromJSPrototype; } } - else if (name.kind === 146 /* QualifiedName */ || name.kind === 185 /* PropertyAccessExpression */) { + else if (name.kind === 146 /* QualifiedName */ || name.kind === 187 /* PropertyAccessExpression */) { var left = name.kind === 146 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 146 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); @@ -31045,6 +31477,12 @@ var ts; var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -31054,10 +31492,19 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId && 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, ts.getMangledNameForScopedPackage(packageId.name)); + var errorInfo = packageId + ? ts.chainDiagnosticMessages( + /*details*/ undefined, typesPackageExists(packageId.name) + ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 + : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } + function typesPackageExists(packageName) { + return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { + return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); + }); }); + } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } @@ -31083,7 +31530,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 277 /* SourceFile */)) { error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); return symbol; } @@ -31194,13 +31641,13 @@ var ts; } function getExportsOfModuleWorker(moduleSymbol) { var visitedSymbols = []; - // A module defined by an 'export=' consists on one export that needs to be resolved + // A module defined by an 'export=' consists of one export that needs to be resolved moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; // 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 & 1955 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { return; } var symbols = ts.cloneMap(symbol.exports); @@ -31245,17 +31692,25 @@ var ts; * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` */ - function getContainerOfSymbol(symbol) { + function getContainersOfSymbol(symbol, enclosingDeclaration) { var container = getParentOfSymbol(symbol); if (container) { - return container; + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + } + return ts.append(additionalContainers, container); } - var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); - if (!candidate) { + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { return undefined; } - var alias = getAliasForSymbolInContainer(candidate, symbol); - return alias ? candidate : undefined; + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { @@ -31279,17 +31734,15 @@ var ts; } } function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var member = members_1[_i]; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; if (member.kind === 155 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } @@ -31316,6 +31769,12 @@ var ts; var type = createType(131072 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; + type.members = undefined; + type.properties = undefined; + type.callSignatures = undefined; + type.constructSignatures = undefined; + type.stringIndexInfo = undefined; + type.numberIndexInfo = undefined; return type; } function createTypeofType() { @@ -31334,25 +31793,19 @@ var ts; function getNamedMembers(members) { var result; members.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - if (symbolIsValue(symbol)) { - result.push(symbol); - } + if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + (result || (result = [])).push(symbol); } }); return result || ts.emptyArray; } function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; - type.properties = getNamedMembers(members); + type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); type.callSignatures = callSignatures; type.constructSignatures = constructSignatures; - if (stringIndexInfo) - type.stringIndexInfo = stringIndexInfo; - if (numberIndexInfo) - type.numberIndexInfo = numberIndexInfo; + type.stringIndexInfo = stringIndexInfo; + type.numberIndexInfo = numberIndexInfo; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { @@ -31368,12 +31821,12 @@ var ts; } } switch (location.kind) { - case 274 /* SourceFile */: + case 277 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -31470,7 +31923,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 252 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -31506,6 +31959,54 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -31516,55 +32017,20 @@ var ts; */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, - }; - } - return hasAccessibleDeclarations; - } - else { - if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { - // Any meaning of a module symbol is always accessible via an `import` type - return { - accessibility: 0 /* Accessible */ - }; - } - } - // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. - // It could be a qualified symbol and hence verify the path - // e.g.: - // module m { - // export class c { - // } - // } - // const x: typeof m.c - // In the above example when we start with checking if typeof m.c symbol is accessible, - // we are going to see if c can be accessed in scope directly. - // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible - // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getContainerOfSymbol(symbol); + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { accessibility: 2 /* CannotBeNamed */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), errorModuleName: symbolToString(symbolExternalModule) }; } @@ -31572,20 +32038,20 @@ var ts; // Just a local name that is not accessible return { accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 /* Accessible */ }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 274 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 274 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -31638,8 +32104,8 @@ var ts; // Typeof value meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 185 /* PropertyAccessExpression */ || - entityName.parent.kind === 243 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || + entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -31700,7 +32166,8 @@ var ts; function typeToString(type, enclosingDeclaration, flags, writer) { if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -31708,7 +32175,7 @@ var ts; var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } @@ -31721,71 +32188,48 @@ var ts; function createNodeBuilder() { return { typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = typeToTypeNodeHelper(type, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); }); }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; // TODO: GH#18217 + return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); }); }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); }); }, symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); }); }, symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = symbolToExpression(symbol, context, meaning); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); }); }, symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); }); }, symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = symbolToParameterDeclaration(symbol, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); }); }, typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = typeParameterToDeclaration(parameter, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); }); }, }; - function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { - return { + function withContext(enclosingDeclaration, flags, tracker, cb) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, - inferTypeParameters: undefined + inferTypeParameters: undefined, + approximateLength: 0 }; + var resultingNode = cb(context); + return context.encounteredError ? undefined : resultingNode; + } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; } function typeToTypeNodeHelper(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { @@ -31798,66 +32242,83 @@ var ts; return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { return ts.createKeywordTypeNode(142 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(137 /* StringKeyword */); } if (type.flags & 8 /* Number */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(134 /* NumberKeyword */); } if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (type.flags & (64 /* StringLiteral */)) { + if (type.flags & 64 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & (128 /* NumberLiteral */)) { + if (type.flags & 128 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 256 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 2048 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } + context.approximateLength += 13; return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); } if (type.flags & 4096 /* Void */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(105 /* VoidKeyword */); } if (type.flags & 8192 /* Undefined */) { + context.approximateLength += 9; return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); } if (type.flags & 16384 /* Null */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(95 /* NullKeyword */); } if (type.flags & 32768 /* Never */) { + context.approximateLength += 5; return ts.createKeywordTypeNode(131 /* NeverKeyword */); } if (type.flags & 1024 /* ESSymbol */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(138 /* SymbolKeyword */); } if (type.flags & 16777216 /* NonPrimitive */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(135 /* ObjectKeyword */); } if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { @@ -31869,6 +32330,7 @@ var ts; context.tracker.reportInaccessibleThisError(); } } + context.approximateLength += 4; return ts.createThis(); } var objectFlags = ts.getObjectFlags(type); @@ -31878,6 +32340,7 @@ var ts; } if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && @@ -31886,7 +32349,9 @@ var ts; ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { - return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol @@ -31901,9 +32366,9 @@ var ts; } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; - var typeNodes = mapToTypeNodes(types, context); + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 169 /* UnionType */ : 170 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { @@ -31920,12 +32385,14 @@ var ts; } if (type.flags & 1048576 /* Index */) { var indexedType = type.type; + context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 2097152 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } if (type.flags & 4194304 /* Conditional */) { @@ -31936,6 +32403,7 @@ var ts; context.inferTypeParameters = saveInferTypeParameters; var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 8388608 /* Substitution */) { @@ -31958,6 +32426,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { @@ -31966,13 +32435,13 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects - else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 205 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, 67216319 /* Value */); @@ -31985,6 +32454,7 @@ var ts; return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); } else { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } } @@ -32010,7 +32480,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 274 /* SourceFile */ || declaration.parent.kind === 240 /* ModuleBlock */; + return declaration.parent.kind === 277 /* SourceFile */ || declaration.parent.kind === 243 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -32026,6 +32496,7 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { @@ -32044,6 +32515,7 @@ var ts; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function typeReferenceToTypeNode(type) { @@ -32058,8 +32530,15 @@ var ts; } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); + var arity = getTypeReferenceArity(type); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + var hasRestElement = type.target.hasRestElement; if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { + for (var i = type.target.minLength; i < arity; i++) { + tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? + ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : + ts.createOptionalTypeNode(tupleConstituentNodes[i]); + } return ts.createTupleTypeNode(tupleConstituentNodes); } } @@ -32153,6 +32632,9 @@ var ts; return ids; } function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; @@ -32175,8 +32657,10 @@ var ts; if (!properties) { return typeElements; } + var i = 0; for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + i++; if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { if (propertySymbol.flags & 4194304 /* Prototype */) { continue; @@ -32185,61 +32669,96 @@ var ts; context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); } } - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? - anyType : getTypeOfSymbol(propertySymbol); - var saveEnclosingDeclaration = context.enclosingDeclaration; - context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } - } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); - context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; - if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { - var signatures = getSignaturesOfType(propertyType, 0 /* Call */); - for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { - var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); - } - typeElements.push(methodDeclaration); - } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); } - else { - var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; - var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined); - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); - } - typeElements.push(propertySignature); + } + } + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); } + typeElements.push(methodDeclaration); } - return typeElements.length ? typeElements : undefined; + } + else { + var savedFlags = context.flags; + context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); } } - function mapToTypeNodes(types, context) { + function mapToTypeNodes(types, context, isBareList) { if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } var result = []; + var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -32261,6 +32780,7 @@ var ts; if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } + context.approximateLength += (name.length + 4); return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } @@ -32273,7 +32793,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -32299,6 +32819,7 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { @@ -32320,14 +32841,14 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 293 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32335,7 +32856,7 @@ var ts; } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; - var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -32344,17 +32865,19 @@ var ts; cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); - var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var questionToken = isOptional ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 182 /* BindingElement */) { + if (clone.kind === 184 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); @@ -32377,16 +32900,18 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); - var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents)) { + for (var _i = 0, _a = parents; _i < _a.length; _i++) { + var parent = _a[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } } } } @@ -32396,10 +32921,12 @@ var ts; if ( // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } return [symbol]; } } @@ -32438,17 +32965,55 @@ var ts; } return top; } + function getSpecifierForModuleSymbol(symbol, context) { + var file = ts.getDeclarationOfKind(symbol, 277 /* SourceFile */); + if (file && file.moduleName !== undefined) { + // Use the amd name if it is available + return file.moduleName; + } + if (!file) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl, symbol); + } + } + } + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; + } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - context.flags |= 16777216 /* InInitialEntityName */; - var rootName = getNameOfSymbolAsWritten(chain[0], context); - context.flags ^= 16777216 /* InInitialEntityName */; var isTypeOf = meaning === 67216319 /* Value */; - if (ambientModuleSymbolRegex.test(rootName)) { + if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); - var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") if (!nonRootParts || ts.isEntityName(nonRootParts)) { if (nonRootParts) { var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; @@ -32482,6 +33047,7 @@ var ts; context.flags |= 16777216 /* InInitialEntityName */; } var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } @@ -32622,8 +33188,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 173 /* ParenthesizedType */; }); - if (node.kind === 237 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175 /* ParenthesizedType */; }); + if (node.kind === 240 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -32631,11 +33197,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 240 /* ModuleBlock */ && + node.parent.kind === 243 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 274 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location); } /** * Gets a human-readable name for a symbol. @@ -32655,42 +33221,22 @@ var ts; return "default"; } if (symbol.declarations && symbol.declarations.length) { - if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) { // TODO: GH#18217 - var file = ts.getDeclarationOfKind(symbol, 274 /* SourceFile */); - if (!file || !context.tracker.moduleResolverHost) { - if (context.tracker.trackReferencedAmbientModule) { - var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); - if (ts.length(ambientDecls)) { - for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { - var decl = ambientDecls_1[_i]; - context.tracker.trackReferencedAmbientModule(decl); // TODO: GH#18217 - } - } - } - // ambient module, just use declaration/symbol name (fallthrough) - } - else { - var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); - return "\"" + (file.moduleName || ts.moduleSpecifiers.getModuleSpecifier(compilerOptions, contextFile, contextFile.path, file.path, context.tracker.moduleResolverHost)) + "\""; - } - } var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); if (name) { return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 232 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 235 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { - context.encounteredError = true; - } switch (declaration.kind) { - case 205 /* ClassExpression */: - return "(Anonymous class)"; - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: - return "(Anonymous function)"; + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + } + return declaration.kind === 207 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var nameType = symbol.nameType; @@ -32715,27 +33261,27 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 292 /* JSDocCallbackTag */: - case 297 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 182 /* BindingElement */: + case 184 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 239 /* ModuleDeclaration */: - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 234 /* FunctionDeclaration */: - case 238 /* EnumDeclaration */: - case 243 /* ImportEqualsDeclaration */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 237 /* FunctionDeclaration */: + case 241 /* EnumDeclaration */: + case 246 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -32743,7 +33289,7 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 243 /* ImportEqualsDeclaration */ && parent.kind !== 274 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + !(node.kind !== 246 /* ImportEqualsDeclaration */ && parent.kind !== 277 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible @@ -32765,31 +33311,31 @@ var ts; case 158 /* CallSignature */: case 160 /* IndexSignature */: case 149 /* Parameter */: - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: case 163 /* FunctionType */: case 164 /* ConstructorType */: case 166 /* TypeLiteral */: case 162 /* TypeReference */: case 167 /* ArrayType */: case 168 /* TupleType */: - case 169 /* UnionType */: - case 170 /* IntersectionType */: - case 173 /* ParenthesizedType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 175 /* ParenthesizedType */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 245 /* ImportClause */: - case 246 /* NamespaceImport */: - case 248 /* ImportSpecifier */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: return false; // Type parameters are always visible case 148 /* TypeParameter */: // Source file and namespace export are always visible - case 274 /* SourceFile */: - case 242 /* NamespaceExportDeclaration */: + case 277 /* SourceFile */: + case 245 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return false; default: return false; @@ -32798,10 +33344,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 249 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 252 /* ExportSpecifier */) { + else if (node.parent.kind === 255 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; @@ -32869,23 +33415,19 @@ var ts; return -1; } function hasType(target, propertyName) { - if (propertyName === 0 /* Type */) { - return !!getSymbolLinks(target).type; - } - if (propertyName === 2 /* DeclaredType */) { - return !!getSymbolLinks(target).declaredType; - } - if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return !!target.resolvedBaseConstructorType; - } - if (propertyName === 3 /* ResolvedReturnType */) { - return !!target.resolvedReturnType; - } - if (propertyName === 4 /* ResolvedBaseConstraint */) { - var bc = target.resolvedBaseConstraint; - return !!bc && bc !== circularConstraintType; - } - return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + } + return ts.Debug.assertNever(propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -32897,12 +33439,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 232 /* VariableDeclaration */: - case 233 /* VariableDeclarationList */: - case 248 /* ImportSpecifier */: - case 247 /* NamedImports */: - case 246 /* NamespaceImport */: - case 245 /* ImportClause */: + case 235 /* VariableDeclaration */: + case 236 /* VariableDeclarationList */: + case 251 /* ImportSpecifier */: + case 250 /* NamedImports */: + case 249 /* NamespaceImport */: + case 248 /* ImportClause */: return false; default: return true; @@ -32932,7 +33474,7 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); @@ -32950,10 +33492,9 @@ var ts; } for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; - var inNamesToRemove = names.has(prop.escapedName); - var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); - var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); - if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { + if (!names.has(prop.escapedName) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { members.set(prop.escapedName, getNonReadonlySymbol(prop)); } } @@ -32979,7 +33520,7 @@ var ts; return parentType; } var type; - if (pattern.kind === 180 /* ObjectBindingPattern */) { + if (pattern.kind === 182 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); @@ -33049,22 +33590,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + var index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // Rest element has an array type with the same element type as the parent type - type = createArrayType(elementType); + // If the parent is a tuple type, the rest element has an array type with a union of the + // remaining tuple element types. Otherwise, the rest element has an array type with same + // element type as the parent type. + type = isTupleType(parentType) ? + getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) - ? getTypeOfPropertyOfType(parentType, propName) - : elementType; + var index_1 = pattern.elements.indexOf(declaration); + type = isTupleLikeType(parentType) ? + getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); } return errorType; } @@ -33075,7 +33621,7 @@ var ts; if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } - return declaration.initializer ? + return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : type; } @@ -33092,7 +33638,7 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 183 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 185 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -33102,11 +33648,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 221 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224 /* ForInStatement */) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); return indexType.flags & (65536 /* TypeParameter */ | 1048576 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 222 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -33125,7 +33671,7 @@ var ts; return addOptionality(declaredType, isOptional); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 232 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no @@ -33156,17 +33702,17 @@ var ts; } } // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.escapedName === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } + else if (ts.isInJavaScriptFile(declaration)) { + var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); + if (expandoType) { + return expandoType; + } + } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); @@ -33184,96 +33730,46 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); if (specialDeclaration) { - return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var tag = ts.getJSDocTypeTag(specialDeclaration); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); + return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); } - var types = []; - var constructorTypes; var definedInConstructor = false; var definedInMethod = false; - var jsDocType; - var _loop_1 = function (declaration) { - var declarationInConstructor = false; - var expression = declaration.kind === 200 /* BinaryExpression */ ? declaration : - declaration.kind === 185 /* PropertyAccessExpression */ ? ts.cast(declaration.parent, ts.isBinaryExpression) : + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { - return { value: errorType }; + return errorType; } - var special = ts.getSpecialPropertyAssignmentKind(expression); + var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); if (special === 4 /* ThisProperty */) { - var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); - // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. - // Function expressions that are assigned to the prototype count as methods. - declarationInConstructor = thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 234 /* FunctionDeclaration */ || - (thisContainer.kind === 192 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); - if (declarationInConstructor) { + if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } else { definedInMethod = true; } } - // If there is a JSDoc type, use it - var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type_1) { - var declarationType = getWidenedType(type_1); - if (!jsDocType) { - jsDocType = declarationType; - } - else if (jsDocType !== errorType && declarationType !== errorType && - !isTypeIdenticalTo(jsDocType, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { - errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); - } - } - else if (!jsDocType) { - // If we don't have an explicit JSDoc type, get the type from the expression. - var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); - if (ts.getObjectFlags(type_2) & 16 /* Anonymous */ && - special === 2 /* ModuleExports */ && - symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type_2); - var members_2 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_2); - symbol.exports.forEach(function (s, name) { - if (members_2.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_2.set(name, union); - } - else { - members_2.set(name, s); - } - }); - type_2 = createAnonymousType(exportedType_1.symbol, members_2, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); - } - var anyedType = type_2; - if (isEmptyArrayLiteralType(type_2)) { - anyedType = anyArrayType; - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } - } - types.push(anyedType); - if (declarationInConstructor) { - (constructorTypes || (constructorTypes = [])).push(anyedType); - } + jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!jsdocType) { + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); } - }; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var state_2 = _loop_1(declaration); - if (typeof state_2 === "object") - return state_2.value; } - var type = jsDocType; + var type = jsdocType; if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfSpecialPropertyOfBaseType(symbol); @@ -33294,6 +33790,91 @@ var ts; } return widened; } + function getJSExpandoObjectType(decl, symbol, init) { + if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 131072 /* Object */ && + special === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 155 /* Constructor */ || + thisContainer.kind === 237 /* FunctionDeclaration */ || + (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } /** check for definition in base class if any declaration is in a class */ function getTypeOfSpecialPropertyOfBaseType(specialProperty) { var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { @@ -33313,7 +33894,7 @@ var ts; // pattern. Otherwise, it is the type any. function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { - return checkDeclarationInitializer(element); + return addOptionality(checkDeclarationInitializer(element)); } if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); @@ -33358,12 +33939,13 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - if (!lastElement || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + var hasRestElement = !!(lastElement && lastElement.kind === 184 /* BindingElement */ && lastElement.dotDotDotToken); + if (elements.length === 0 || elements.length === 1 && hasRestElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } - // If the pattern has at least one element, and no rest element, then it should imply a tuple type. var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); + var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1; + var result = createTupleType(elementTypes, minLength, hasRestElement); if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; @@ -33380,7 +33962,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 180 /* ObjectBindingPattern */ + return pattern.kind === 182 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -33394,7 +33976,9 @@ var ts; // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); @@ -33428,100 +34012,104 @@ var ts; } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - // Handle prototype property - if (symbol.flags & 4194304 /* Prototype */) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - // CommonsJS require and module both have type any. - if (symbol === requireSymbol || symbol === moduleSymbol) { - return links.type = anyType; - } - // Handle catch clause variables - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; - } - if (declaration.kind === 249 /* ExportAssignment */) { - return links.type = checkExpression(declaration.expression); - } - if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } - // Handle variable, parameter or property - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; - } - var type = void 0; - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - if (declaration.kind === 200 /* BinaryExpression */ || - declaration.kind === 185 /* PropertyAccessExpression */ && declaration.parent.kind === 200 /* BinaryExpression */) { - type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else if (ts.isJSDocPropertyLikeTag(declaration) - || ts.isPropertyAccessExpression(declaration) - || ts.isIdentifier(declaration) - || ts.isClassDeclaration(declaration) - || ts.isFunctionDeclaration(declaration) - || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { - // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - return getTypeOfFuncClassEnumModule(symbol); - } - type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; - } - else if (ts.isPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); - } - else if (ts.isJsxAttribute(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); - } - else if (ts.isShorthandPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); - } - else if (ts.isObjectLiteralMethod(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); - } - else if (ts.isParameter(declaration) - || ts.isPropertyDeclaration(declaration) - || ts.isPropertySignature(declaration) - || ts.isVariableDeclaration(declaration) - || ts.isBindingElement(declaration)) { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); - } - else { - return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); + } + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); } - return links.type; + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } + if (declaration.kind === 252 /* ExportAssignment */) { + return checkExpression(declaration.expression); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJavaScriptFile(declaration) && + (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromJSPropertyAssignments(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + return type; } - function getAnnotatedAccessorType(accessor) { + function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { if (accessor.kind === 156 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); - return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + return getterTypeAnnotation; } else { var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + return setterTypeAnnotation; } } return undefined; } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } function getAnnotatedAccessorThisParameter(accessor) { var parameter = getAccessorThisParameter(accessor); return parameter && parameter.symbol; @@ -33531,60 +34119,60 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; } - var type = void 0; - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; } else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); } + // Otherwise, fall back to 'any'. else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } - type = anyType; } + type = anyType; } } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); - } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } - links.type = type; } - return links.type; + return type; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -33592,6 +34180,7 @@ var ts; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); + var originalLinks = links; if (!links.type) { var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); if (jsDeclaration) { @@ -33610,32 +34199,45 @@ var ts; } } } - if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else if (symbol.valueDeclaration.kind === 200 /* BinaryExpression */ || - symbol.valueDeclaration.kind === 185 /* PropertyAccessExpression */ && symbol.valueDeclaration.parent.kind === 200 /* BinaryExpression */) { - links.type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - var type = createObjectType(16 /* Anonymous */, symbol); - if (symbol.flags & 32 /* Class */) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 202 /* BinaryExpression */ || + declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { + return getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; } - else { - links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); } + return type_1; } } - return links.type; + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } } function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); } function getTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); @@ -33661,7 +34263,7 @@ var ts; } else { if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type = errorType; } symbolInstantiationDepth++; var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); @@ -33737,8 +34339,8 @@ var ts; // 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 appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { - var declaration = declarations_1[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); } return typeParameters; @@ -33751,35 +34353,35 @@ var ts; return undefined; } switch (node.kind) { - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 236 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: case 158 /* CallSignature */: case 159 /* ConstructSignature */: case 153 /* MethodSignature */: case 163 /* FunctionType */: case 164 /* ConstructorType */: - case 284 /* JSDocFunctionType */: - case 234 /* FunctionDeclaration */: + case 287 /* JSDocFunctionType */: + case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: - case 237 /* TypeAliasDeclaration */: - case 296 /* JSDocTemplateTag */: - case 297 /* JSDocTypedefTag */: - case 292 /* JSDocCallbackTag */: - case 177 /* MappedType */: - case 171 /* ConditionalType */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 240 /* TypeAliasDeclaration */: + case 301 /* JSDocTemplateTag */: + case 302 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 179 /* MappedType */: + case 173 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 177 /* MappedType */) { + if (node.kind === 179 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 171 /* ConditionalType */) { + else if (node.kind === 173 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 235 /* ClassDeclaration */ || node.kind === 205 /* ClassExpression */ || node.kind === 236 /* InterfaceDeclaration */) && + (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */ || node.kind === 239 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -33787,7 +34389,7 @@ var ts; } // 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, 236 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -33796,9 +34398,9 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 236 /* InterfaceDeclaration */ || - node.kind === 235 /* ClassDeclaration */ || - node.kind === 205 /* ClassExpression */ || + if (node.kind === 239 /* InterfaceDeclaration */ || + node.kind === 238 /* ClassDeclaration */ || + node.kind === 207 /* ClassExpression */ || ts.isTypeAlias(node)) { var declaration = node; result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); @@ -33829,23 +34431,18 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return false; + return isJavascriptConstructorType(type); } function getBaseTypeNodeOfClass(type) { - var decl = type.symbol.valueDeclaration; - if (ts.isInJavaScriptFile(decl)) { - // Prefer an @augments tag because it may have type parameters. - var tag = ts.getJSDocAugmentsTag(decl); - if (tag) { - return tag.class; - } - } - return ts.getClassExtendsHeritageClauseElement(decl); + return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + var isJavascript = ts.isInJavaScriptFile(location); + if (isJavascriptConstructorType(type) && !typeArgCount) { + return getSignaturesOfType(type, 0 /* Call */); + } + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); @@ -33863,7 +34460,7 @@ var ts; function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { var decl = type.symbol.valueDeclaration; - var extended = ts.getClassExtendsHeritageClauseElement(decl); + var extended = ts.getEffectiveBaseTypeNode(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; @@ -33896,7 +34493,7 @@ var ts; function getBaseTypes(type) { if (!type.resolvedBaseTypes) { if (type.objectFlags & 8 /* Tuple */) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { if (type.symbol.flags & 32 /* Class */) { @@ -33932,6 +34529,9 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } + else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere @@ -33959,7 +34559,7 @@ var ts; // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a // partial instantiation of the members without the base types fully resolved - type.members = undefined; // TODO: GH#18217 + type.members = undefined; } return type.resolvedBaseTypes = [baseType]; } @@ -33984,7 +34584,7 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 236 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 239 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -34020,7 +34620,7 @@ var ts; function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 236 /* InterfaceDeclaration */) { + if (declaration.kind === 239 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -34078,7 +34678,7 @@ var ts; return errorType; } var declaration = ts.find(symbol.declarations, function (d) { - return ts.isJSDocTypeAlias(d) || d.kind === 237 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 240 /* TypeAliasDeclaration */; }); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. @@ -34105,7 +34705,7 @@ var ts; if (expr.kind === 9 /* StringLiteral */) { return true; } - else if (expr.kind === 200 /* BinaryExpression */) { + else if (expr.kind === 202 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -34119,12 +34719,12 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 71 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -34138,7 +34738,7 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 238 /* EnumDeclaration */) { + if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { @@ -34165,7 +34765,7 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 238 /* EnumDeclaration */) { + if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 @@ -34255,7 +34855,7 @@ var ts; case 140 /* UndefinedKeyword */: case 95 /* NullKeyword */: case 131 /* NeverKeyword */: - case 178 /* LiteralType */: + case 180 /* LiteralType */: return true; case 167 /* ArrayType */: return isThislessType(node.elementType); @@ -34266,7 +34866,8 @@ var ts; } /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ function isThislessTypeParameter(node) { - return !node.constraint || isThislessType(node.constraint); + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); } /** * A variable-like declaration is free of this references if it has a type annotation @@ -34316,8 +34917,8 @@ var ts; // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { var result = ts.createSymbolTable(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper)); } return result; @@ -34364,6 +34965,11 @@ var ts; && ts.isEntityNameExpression(node.expression) && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } /** * Indicates whether a declaration has a late-bindable dynamic name. */ @@ -34467,9 +35073,9 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_1 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_1); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_1); + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); } lateSymbol.nameType = type; @@ -34502,8 +35108,8 @@ var ts; var decl = _a[_i]; var members = ts.getMembersOfDeclaration(decl); if (members) { - for (var _b = 0, members_3 = members; _b < members_3.length; _b++) { - var member = members_3[_b]; + for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { + var member = members_4[_b]; if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); } @@ -34635,6 +35241,28 @@ var ts; return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } + function getExpandedParameters(sig) { + if (sig.hasRestParameter) { + var restIndex_1 = sig.parameters.length - 1; + var restParameter = sig.parameters[restIndex_1]; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var elementTypes = restType.typeArguments || ts.emptyArray; + var minLength_1 = restType.target.minLength; + var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; + var restParams = ts.map(elementTypes, function (t, i) { + var name = getParameterNameAtPosition(sig, restIndex_1 + i); + var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : + i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); + symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; + return symbol; + }); + return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams); + } + } + return sig.parameters; + } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); @@ -34779,7 +35407,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_2 = function (i) { + var _loop_4 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -34802,7 +35430,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_2(i); + _loop_4(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -34812,6 +35440,7 @@ var ts; function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; if (type.target) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); @@ -34820,6 +35449,7 @@ var ts; setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048 /* TypeLiteral */) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var members = getMembersOfSymbol(symbol); var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); @@ -34904,7 +35534,7 @@ var ts; // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), /*_index*/ undefined, prop); + addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -34922,7 +35552,7 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - function addMemberForKeyType(t, _index, origin) { + function addMemberForKeyType(t) { // 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. @@ -34944,9 +35574,9 @@ var ts; prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : propType; - if (origin) { - prop.syntheticOrigin = origin; - prop.declarations = origin.declarations; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; } prop.nameType = t; members.set(propName, prop); @@ -34974,11 +35604,11 @@ var ts; errorType); } function getConstraintDeclarationForMappedType(type) { - return type.declaration.typeParameter.constraint; + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 175 /* TypeOperator */ && + return constraintDeclaration.kind === 177 /* TypeOperator */ && constraintDeclaration.operator === 128 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { @@ -35098,6 +35728,13 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + return obj.properties.some(function (property) { + var name = property.name && ts.getTextOfPropertyName(property.name); + var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + }); + } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); if (!(unionType.flags & 262144 /* Union */)) { @@ -35204,20 +35841,12 @@ var ts; } return undefined; } - function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { + function getBaseConstraintOfType(type) { if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } - } - } - function getBaseConstraintOfType(type) { - var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); - if (!constraint && type.flags & 1048576 /* Index */) { - return keyofConstraintType; + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return constraint; + return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35235,23 +35864,24 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var circular; - if (!type.resolvedBaseConstraint) { - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + var result = computeBaseConstraint(getSimplifiedType(t)); + if (!popTypeResolution()) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; } - return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { - circular = true; - return undefined; - } - var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { - circular = true; - return undefined; - } - return result; + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { if (t.flags & 65536 /* TypeParameter */) { @@ -35264,8 +35894,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_3 = types_4[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_4[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -35360,6 +35990,7 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; + var indexTypes; var isUnion = containingType.flags & 262144 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols @@ -35385,14 +36016,21 @@ var ts; } } else if (isUnion) { - checkFlags |= 16 /* Partial */; + var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); + if (index) { + checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, index.type); + } + else { + checkFlags |= 16 /* Partial */; + } } } } if (!props) { return undefined; } - if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } var declarations; @@ -35424,6 +36062,7 @@ var ts; } propTypes.push(type); } + ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && commonValueDeclaration) { @@ -35555,10 +36194,10 @@ var ts; function isJSDocOptionalParameter(node) { return ts.isInJavaScriptFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 283 /* JSDocOptionalType */ + node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 283 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -35577,7 +36216,7 @@ var ts; var signature = getSignatureFromDeclaration(node.parent); var parameterIndex = node.parent.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); - return parameterIndex >= signature.minArgumentCount; + return parameterIndex >= getMinArgumentCount(signature); } var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); if (iife) { @@ -35592,18 +36231,7 @@ var ts; return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 283 /* JSDocOptionalType */; - } - function createTypePredicateFromTypePredicateNode(node) { - var parameterName = node.parameterName; - var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { - return createIdentifierTypePredicate(parameterName && parameterName.escapedText, // TODO: GH#18217 - parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); - } - else { - return createThisTypePredicate(type); - } + return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -35680,14 +36308,14 @@ var ts; var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } - if (i === 0 && paramSymbol.escapedName === "this") { + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { hasThisParameter = true; thisParameter = param.symbol; } else { parameters.push(paramSymbol); } - if (type && type.kind === 178 /* LiteralType */) { + if (type && type.kind === 180 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter @@ -35714,9 +36342,9 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -35735,9 +36363,8 @@ var ts; var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; - syntheticArgsSymbol.isRestParameter = true; if (lastParamVariadicType) { // Replace the last parameter with a rest parameter. parameters.pop(); @@ -35745,26 +36372,14 @@ var ts; parameters.push(syntheticArgsSymbol); return true; } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 - } - else if (classType) { - return classType; - } - var typeNode = ts.getEffectiveReturnTypeNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); - } - // TypeScript 1.0 spec (April 2014): - // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); } function containsArgumentsReference(declaration) { var links = getNodeLinks(declaration); @@ -35843,61 +36458,111 @@ var ts; signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; } else { - var declaration = signature.declaration; - signature.resolvedTypePredicate = declaration && declaration.type && declaration.type.kind === 161 /* TypePredicate */ ? - createTypePredicateFromTypePredicateNode(declaration.type) : - noTypePredicate; + var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJavaScriptFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } + signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 71 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + type = anyType; } signature.resolvedReturnType = type; } return signature.resolvedReturnType; } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 155 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } function isResolvingReturnTypeOfSignature(signature) { return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.last(signature.parameters)); - if (ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { - return type.typeArguments[0]; - } - } - return anyType; + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + var type = getTypeOfRestParameter(signature); + return type && getIndexTypeOfType(type, 1 /* Number */); } function getSignatureInstantiation(signature, typeArguments, isJavascript) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript); + return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); var id = getTypeListId(typeArguments); var instantiation = instantiations.get(id); @@ -35992,44 +36657,53 @@ var ts; } function getConstraintDeclaration(type) { var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); - return decl && decl.constraint; + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { var inferences; if (typeParameter.symbol) { for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - // When an 'infer T' declaration is immediately contained in a type reference node - // (such as 'Foo'), T's constraint is inferred from the constraint of the - // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are - // present, we form an intersection of the inferred constraint types. - if (declaration.parent.kind === 172 /* InferType */ && declaration.parent.parent.kind === 162 /* TypeReference */) { - var typeReference = declaration.parent.parent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(declaration.parent); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); - if (declaredConstraint) { - // Type parameter constraints can reference other type parameters so - // constraints need to be instantiated. If instantiation produces the - // type parameter itself, we discard that inference. For example, in - // type Foo = [T, U]; - // type Bar = T extends Foo ? Foo : T; - // the instantiated constraint for U is X, so we discard that inference. - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); - var constraint = instantiateType(declaredConstraint, mapper); - if (constraint !== typeParameter) { - inferences = ts.append(inferences, constraint); + if (declaration.parent.kind === 174 /* InferType */) { + // When an 'infer T' declaration is immediately contained in a type reference node + // (such as 'Foo'), T's constraint is inferred from the constraint of the + // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are + // present, we form an intersection of the inferred constraint types. + var grandParent = declaration.parent.parent; + if (grandParent.kind === 162 /* TypeReference */) { + var typeReference = grandParent; + var typeParameters = getTypeParametersForTypeReference(typeReference); + if (typeParameters) { + var index = typeReference.typeArguments.indexOf(declaration.parent); + if (index < typeParameters.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + // Type parameter constraints can reference other type parameters so + // constraints need to be instantiated. If instantiation produces the + // type parameter itself, we discard that inference. For example, in + // type Foo = [T, U]; + // type Bar = T extends Foo ? Foo : T; + // the instantiated constraint for U is X, so we discard that inference. + var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = ts.append(inferences, constraint); + } } } } } + // When an 'infer T' declaration is immediately contained in a rest parameter + // declaration, we infer an 'unknown[]' constraint. + else if (grandParent.kind === 149 /* Parameter */ && grandParent.dotDotDotToken) { + inferences = ts.append(inferences, createArrayType(unknownType)); + } } } } return inferences && getIntersectionType(inferences); } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { if (typeParameter.target) { @@ -36045,7 +36719,9 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */).parent); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); } function getTypeListId(types) { var result = ""; @@ -36119,7 +36795,7 @@ var ts; var isJs = ts.isInJavaScriptFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 290 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36178,7 +36854,7 @@ var ts; switch (node.kind) { case 162 /* TypeReference */: return node.typeName; - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -36235,6 +36911,10 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } + var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag && enumTag.typeExpression) { + return getTypeFromTypeNode(enumTag.typeExpression); + } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -36271,9 +36951,9 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 286 /* JSDocComment */) { + while (node && !ts.isStatement(node) && node.kind !== 289 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 171 /* ConditionalType */ && node === parent.trueType) { + if (parent.kind === 173 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -36284,7 +36964,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 162 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -36375,19 +37055,19 @@ var ts; // The expression is processed as an identifier expression (section 4.3) // or property access expression(section 4.10), // the widened type(section 3.9) of which becomes the result. - links.resolvedType = getWidenedType(checkExpression(node.exprName)); + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); } return links.resolvedType; } function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { - var declaration = declarations_2[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 238 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: return declaration; } } @@ -36494,6 +37174,9 @@ var ts; function createArrayType(elementType) { return createTypeFromGenericGlobalType(globalArrayType, [elementType]); } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -36508,18 +37191,26 @@ var ts; // // Note that the generic type created by this function has no symbol associated with it. The same // is true for each of the synthesized type parameters. - function createTupleTypeOfArity(arity) { - var typeParameters = []; + function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var typeParameters; var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(65536 /* TypeParameter */); - typeParameters.push(typeParameter); - var property = createSymbol(4 /* Property */, "" + i); - property.type = typeParameter; - properties.push(property); + var maxLength = hasRestElement ? arity - 1 : arity; + if (arity) { + typeParameters = new Array(arity); + for (var i = 0; i < arity; i++) { + var typeParameter = typeParameters[i] = createType(65536 /* TypeParameter */); + if (i < maxLength) { + var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); + property.type = typeParameter; + properties.push(property); + } + } } + var literalTypes = []; + for (var i = minLength; i <= maxLength; i++) + literalTypes.push(getLiteralType(i)); var lengthSymbol = createSymbol(4 /* Property */, "length"); - lengthSymbol.type = getLiteralType(arity); + lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes); properties.push(lengthSymbol); var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); type.typeParameters = typeParameters; @@ -36537,27 +37228,61 @@ var ts; type.declaredConstructSignatures = ts.emptyArray; type.declaredStringIndexInfo = undefined; type.declaredNumberIndexInfo = undefined; + type.minLength = minLength; + type.hasRestElement = hasRestElement; + type.associatedNames = associatedNames; return type; } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + var type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + } + return type; } - function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + if (minLength === void 0) { minLength = elementTypes.length; } + if (hasRestElement === void 0) { hasRestElement = false; } + var arity = elementTypes.length; + if (arity === 1 && hasRestElement) { + return createArrayType(elementTypes[0]); + } + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + var lastElement = ts.lastOrUndefined(node.elementTypes); + var restElement_1 = lastElement && lastElement.kind === 170 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 /* OptionalType */ && n !== restElement_1; }) + 1; + var elementTypes = ts.map(node.elementTypes, function (n) { + var type = getTypeFromTypeNode(n); + return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; + }); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); } return links.resolvedType; } + function getTypeFromOptionalTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getOptionalType(type) : type; + } function getTypeId(type) { return type.id; } function containsType(types, type) { return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } // Return true if the given intersection type contains // more than one unit type or, // an object type and a nullable type (null or undefined), or @@ -36721,7 +37446,7 @@ var ts; includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, includes & 16749629 /* NotUnit */ ? 0 : 67108864 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -36836,29 +37561,65 @@ var ts; } } } - // When intersecting unions of unit types we can simply intersect based on type identity. - // Here we remove all unions of unit types from the given list and replace them with a - // a single union containing an intersection of the unit types. - function intersectUnionsOfUnitTypes(types) { - var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfUnitTypes */) !== 0; }); - var unionType = types[unionIndex]; - var intersection = unionType.types; - var i = types.length - 1; - var _loop_3 = function () { + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 64 /* StringLiteral */ ? stringType : + type.flags & 128 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfUnitTypes */) { - intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } - i--; - }; - while (i > unionIndex) { - _loop_3(); + else { + i++; + } } - if (intersection === unionType.types) { + // Return false if there was only one union of primitive types + if (!unionTypes) { return false; } - types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 67108864 /* UnionOfUnitTypes */); + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -36898,7 +37659,7 @@ var ts; return typeSet[0]; } if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -36945,7 +37706,7 @@ var ts; if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { - var name = ts.getNameOfDeclaration(prop.valueDeclaration); + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : name && name.kind === 147 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : getLiteralType(ts.symbolName(prop)); @@ -37009,8 +37770,35 @@ var ts; type.indexType = indexType; return type; } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 262144 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 524288 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 15794176 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 186 /* ElementAccessExpression */ ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : @@ -37028,11 +37816,18 @@ var ts; getNodeLinks(accessNode).resolvedSymbol = prop; } } - return getTypeOfSymbol(prop); + var propType = getTypeOfSymbol(prop); + return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + } + if (isTupleType(objectType)) { + var restType = getRestTypeOfTupleType(objectType); + if (restType && isNumericLiteralName(propName) && +propName >= 0) { + return restType; + } } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (isTypeAny(objectType)) { + if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { return objectType; } var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || @@ -37040,7 +37835,7 @@ var ts; undefined; if (indexInfo) { if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { - var indexNode = accessNode.kind === 186 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } else if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { @@ -37051,20 +37846,37 @@ var ts; if (indexType.flags & 32768 /* Never */) { return neverType; } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1 /* Number */)) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); } else { - error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + var suggestion = void 0; + if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== undefined) { + error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } } } return anyType; } } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessNode) { - var indexNode = accessNode.kind === 186 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } @@ -37149,7 +37961,7 @@ var ts; return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 65536 /* TypeParameter */) { - var constraint = getConstraintFromTypeParameter(objectType); + var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); } @@ -37170,7 +37982,7 @@ var ts; // 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 === 186 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } @@ -37310,7 +38122,7 @@ var ts; return true; } while (node) { - if (node.kind === 171 /* ConditionalType */) { + if (node.kind === 173 /* ConditionalType */) { if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { return true; } @@ -37376,19 +38188,17 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var argumentType = getTypeFromTypeNode(node.argument); - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type - var moduleName = argumentType.value; - var innerModuleSymbol = resolveExternalModule(node, moduleName, ts.Diagnostics.Cannot_find_module_0, node, /*isForAugmentation*/ false); + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var moduleSymbol_1 = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); - var currentNamespace = moduleSymbol_1; + var currentNamespace = moduleSymbol; var current = void 0; while (current = nameStack.shift()) { var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; @@ -37404,11 +38214,14 @@ var ts; resolveImportSymbolType(node, links, currentNamespace, targetMeaning); } else { - if (moduleSymbol_1.flags & targetMeaning) { - resolveImportSymbolType(node, links, moduleSymbol_1, targetMeaning); + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - error(node, targetMeaning === 67216319 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here, moduleName); + var errorMessage = targetMeaning === 67216319 /* Value */ + ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here + : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); links.resolvedSymbol = unknownSymbol; links.resolvedType = errorType; } @@ -37494,20 +38307,16 @@ var ts; } for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; - // we approximate own properties as non-methods plus methods that are inside the object literal - var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.escapedName, true); } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + else if (isSpreadableProperty(rightProp)) { members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { var leftProp = _c[_b]; - if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) - || skippedPrivateMembers.has(leftProp.escapedName) - || isClassMethod(leftProp)) { + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { continue; } if (members.has(leftProp.escapedName)) { @@ -37534,6 +38343,12 @@ var ts; spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) + ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) + : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { return prop; @@ -37552,9 +38367,6 @@ var ts; } return index; } - function isClassMethod(prop) { - return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } function createLiteralType(flags, value, symbol) { var type = createType(flags); type.symbol = symbol; @@ -37614,7 +38426,7 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 236 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 239 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && (container.kind !== 155 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -37633,8 +38445,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119 /* AnyKeyword */: - case 279 /* JSDocAllType */: - case 280 /* JSDocUnknownType */: + case 282 /* JSDocAllType */: + case 283 /* JSDocUnknownType */: return anyType; case 142 /* UnknownKeyword */: return unknownType; @@ -37656,16 +38468,16 @@ var ts; return neverType; case 135 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 174 /* ThisType */: + case 176 /* ThisType */: case 99 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 178 /* LiteralType */: + case 180 /* LiteralType */: return getTypeFromLiteralTypeNode(node); case 162 /* TypeReference */: return getTypeFromTypeReference(node); case 161 /* TypePredicate */: return booleanType; - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); case 165 /* TypeQuery */: return getTypeFromTypeQueryNode(node); @@ -37673,45 +38485,48 @@ var ts; return getTypeFromArrayTypeNode(node); case 168 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 169 /* UnionType */: + case 169 /* OptionalType */: + return getTypeFromOptionalTypeNode(node); + case 171 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 170 /* IntersectionType */: + case 172 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 281 /* JSDocNullableType */: + case 284 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 283 /* JSDocOptionalType */: + case 286 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 173 /* ParenthesizedType */: - case 282 /* JSDocNonNullableType */: - case 278 /* JSDocTypeExpression */: + case 175 /* ParenthesizedType */: + case 170 /* RestType */: + case 285 /* JSDocNonNullableType */: + case 281 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 285 /* JSDocVariadicType */: + case 288 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); case 163 /* FunctionType */: case 164 /* ConstructorType */: case 166 /* TypeLiteral */: - case 287 /* JSDocTypeLiteral */: - case 284 /* JSDocFunctionType */: - case 288 /* JSDocSignature */: + case 290 /* JSDocTypeLiteral */: + case 287 /* JSDocFunctionType */: + case 291 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 175 /* TypeOperator */: + case 177 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 176 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 177 /* MappedType */: + case 179 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 171 /* ConditionalType */: + case 173 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 172 /* InferType */: + case 174 /* InferType */: return getTypeFromInferTypeNode(node); - case 179 /* ImportType */: + case 181 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 71 /* Identifier */: case 146 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: return errorType; } @@ -37853,7 +38668,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | (ts.getCheckFlags(symbol) & 1024 /* Late */)); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -37864,11 +38679,6 @@ var ts; if (symbol.nameType) { result.nameType = symbol.nameType; } - if (isTransientSymbol(symbol)) { - if (symbol.isRestParameter) { - result.isRestParameter = symbol.isRestParameter; - } - } return result; } function getAnonymousTypeInstantiation(type, mapper) { @@ -37892,7 +38702,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavaScriptConstructor(declaration_1)) { + if (isJavascriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -37933,14 +38743,14 @@ var ts; // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container_3 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 213 /* Block */ ? "quit" : n === container_3; })) { + if (ts.findAncestor(node, function (n) { return n.kind === 216 /* Block */ ? "quit" : n === container_3; })) { return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { - case 174 /* ThisType */: + case 176 /* ThisType */: return !!tp.isThisType; case 71 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && @@ -37952,11 +38762,16 @@ var ts; } } 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 - // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated - // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for - // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a - // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & 1048576 /* Index */) { var typeVariable_1 = constraintType.type; @@ -37965,7 +38780,11 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); + var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); } return t; }); @@ -37977,6 +38796,25 @@ var ts; function isMappableType(type) { return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + propType; + } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { @@ -38078,32 +38916,32 @@ var ts; function isContextSensitive(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: case 154 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return node.operatorToken.kind === 54 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 263 /* JsxAttributes */: + case 266 /* JsxAttributes */: return ts.some(node.properties, isContextSensitive); - case 262 /* JsxAttribute */: { + case 265 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 265 /* JsxExpression */: { + case 268 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -38120,7 +38958,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 193 /* ArrowFunction */) { + if (node.kind !== 195 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -38128,9 +38966,12 @@ var ts; return true; } } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; - return body.kind === 213 /* Block */ ? false : isContextSensitive(body); + return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -38139,7 +38980,7 @@ var ts; function getTypeWithoutSignatures(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { + if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; @@ -38200,8 +39041,206 @@ var ts; function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + /** + * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to + * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. + */ + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeAssignableTo(source, target)) + return true; + if (!elaborateError(expr, source, target)) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + } + return false; + } + function elaborateError(node, source, target) { + if (!node) + return false; + switch (node.kind) { + case 268 /* JsxExpression */: + case 193 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target); + case 202 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 58 /* EqualsToken */: + case 26 /* CommaToken */: + return elaborateError(node.right, source, target); + } + break; + case 186 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target); + case 185 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target); + case 266 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target); + } + return false; + } + /** + * For every element returned from the iterator, checks that element to issue an error on a property of that element's type + * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` + * Otherwise, we issue an error on _every_ element which fail the assignability check + */ + function elaborateElementwise(iterator, source, target) { + // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span + var reportedError = false; + for (var status = iterator.next(); !status.done; status = iterator.next()) { + var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; + var sourcePropType = getIndexedAccessType(source, nameType); + var targetPropType = getIndexedAccessType(target, nameType); + if (!isTypeAssignableTo(sourcePropType, targetPropType)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + if (elaborated) { + reportedError = true; + } + else { + // Issue error on the prop itself, since the prop couldn't elaborate the error + var resultObj = {}; + // Use the expression type, if available + var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + if (result && specificSource !== sourcePropType) { + // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType + checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + } + if (resultObj.error) { + var reportedDiag = resultObj.error; + var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined; + var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; + var issuedElaboration = false; + if (!targetProp) { + var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + getIndexInfoOfType(target, 0 /* String */) || + undefined; + if (indexInfo && indexInfo.declaration) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } + } + reportedError = true; + } + } + } + return reportedError; + } + function generateJsxAttributes(node) { + var _i, _a, prop; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + prop = _a[_i]; + if (ts.isJsxSpreadAttribute(prop)) + return [3 /*break*/, 3]; + return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateJsxAttributes(node, source, target) { + return elaborateElementwise(generateJsxAttributes(node), source, target); + } + function generateLimitedTupleElements(node, target) { + var len, i, elem, nameType; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + len = ts.length(node.elements); + if (!len) + return [2 /*return*/]; + i = 0; + _a.label = 1; + case 1: + if (!(i < len)) return [3 /*break*/, 4]; + // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature + if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i))) + return [3 /*break*/, 3]; + elem = node.elements[i]; + if (ts.isOmittedExpression(elem)) + return [3 /*break*/, 3]; + nameType = getLiteralType(i); + return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateArrayLiteral(node, source, target) { + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + } + return false; + } + function generateObjectLiteralElements(node) { + var _i, _a, prop, type, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _c.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 8]; + prop = _a[_i]; + if (ts.isSpreadAssignment(prop)) + return [3 /*break*/, 7]; + type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 32768 /* Never */)) { + return [3 /*break*/, 7]; + } + _b = prop.kind; + switch (_b) { + case 157 /* SetAccessor */: return [3 /*break*/, 2]; + case 156 /* GetAccessor */: return [3 /*break*/, 2]; + case 154 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 274 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 273 /* PropertyAssignment */: return [3 /*break*/, 4]; + } + return [3 /*break*/, 6]; + case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; + case 3: + _c.sent(); + return [3 /*break*/, 7]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 5: + _c.sent(); + return [3 /*break*/, 7]; + case 6: + ts.Debug.assertNever(prop); + _c.label = 7; + case 7: + _i++; + return [3 /*break*/, 1]; + case 8: return [2 /*return*/]; + } + }); + } + function elaborateObjectLiteral(node, source, target) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target); } /** * This is *not* a bi-directional relationship. @@ -38222,13 +39261,20 @@ var ts; if (source === target) { return -1 /* True */; } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + var targetCount = getParameterCount(target); + if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0 /* False */; } if (source.typeParameters && source.typeParameters !== target.typeParameters) { target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } + var sourceCount = getParameterCount(source); + var sourceGenericRestType = getGenericRestType(source); + var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; + if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + return 0 /* False */; + } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 /* MethodDeclaration */ && kind !== 153 /* MethodSignature */ && kind !== 155 /* Constructor */; @@ -38249,14 +39295,11 @@ var ts; result &= related; } } - var sourceMax = getNumNonRestParameters(source); - var targetMax = getNumNonRestParameters(target); - var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); - var sourceParams = source.parameters; - var targetParams = target.parameters; - for (var i = 0; i < checkCount; i++) { - var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); - var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); + var paramCount = Math.max(sourceCount, targetCount); + var lastIndex = paramCount - 1; + for (var i = 0; i < paramCount; i++) { + var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); + var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -38275,18 +39318,20 @@ var ts; !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); } return 0 /* False */; } result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? + getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? + getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -38350,30 +39395,6 @@ var ts; } return false; } - function getNumNonRestParameters(signature) { - var numParams = signature.parameters.length; - return signature.hasRestParameter ? - numParams - 1 : - numParams; - } - function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { - if (source.hasRestParameter === target.hasRestParameter) { - if (source.hasRestParameter) { - // If both have rest parameters, get the max and add 1 to - // compensate for the rest parameter. - return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; - } - else { - return Math.min(sourceNonRestParamCount, targetNonRestParamCount); - } - } - else { - // Return the count for whichever signature doesn't have rest parameters. - return source.hasRestParameter ? - targetNonRestParamCount : - sourceNonRestParamCount; - } - } function isEmptyResolvedType(t) { return t.properties.length === 0 && t.callSignatures.length === 0 && @@ -38394,11 +39415,11 @@ var ts; } var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); - if (relation !== undefined) { - return relation; + if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) { + return relation === 1 /* Succeeded */; } if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { - enumRelation.set(id, false); + enumRelation.set(id, 3 /* FailedAndReported */); return false; } var targetEnumType = getTypeOfSymbol(targetSymbol); @@ -38409,13 +39430,16 @@ var ts; if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); + enumRelation.set(id, 3 /* FailedAndReported */); + } + else { + enumRelation.set(id, 2 /* Failed */); } - enumRelation.set(id, false); return false; } } } - enumRelation.set(id, true); + enumRelation.set(id, 1 /* Succeeded */); return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { @@ -38506,7 +39530,7 @@ var ts; * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. * @param containingMessageChain A chain of errors to prepend any new errors found. */ - function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; var maybeKeys; var sourceStack; @@ -38528,18 +39552,24 @@ var ts; errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); // TODO: GH#18217 - } - // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement - if (headMessage && errorNode && !result && source.symbol) { - var links = getSymbolLinks(source.symbol); - if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { - var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); - if (helpfulRetry) { - // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import - diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + var relatedInformation = void 0; + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it + } } } + var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (errorOutputContainer) { + errorOutputContainer.error = diag; + } + diagnostics.add(diag); // TODO: GH#18217 } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { @@ -38621,6 +39651,22 @@ var ts; if (target.flags & 2097152 /* IndexedAccess */) { target = getSimplifiedType(target); } + // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. + // If so, reporting the `null` and `undefined` in the type is hardly useful. + // First, see if we're even relating an object type to a union. + // Then see if the target is stripped down to a single non-union type. + // Note + // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), + // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" + // when dealing with generics. + // * We also don't deal with primitive source types, since we already halt elaboration below. + if (target.flags & 262144 /* Union */ && source.flags & 131072 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 24576 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~24576 /* Nullable */); + if (!(nullStrippedTarget.flags & (262144 /* Union */ | 32768 /* Never */))) { + target = nullStrippedTarget; + } + } // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if (source === target) return -1 /* True */; @@ -38790,6 +39836,9 @@ var ts; return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && @@ -38800,7 +39849,7 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_4 = function (prop) { + var _loop_5 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -38839,9 +39888,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_4(prop); - if (typeof state_3 === "object") - return state_3.value; + var state_2 = _loop_5(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -38872,11 +39921,35 @@ var ts; } } if (reportErrors) { - var discriminantType = findMatchingDiscriminantType(source, target); - isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + var bestMatchingType = findMatchingDiscriminantType(source, target) || + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target); + isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + var sourceObjectFlags = ts.getObjectFlags(source); + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 262144 /* Union */) { + return ts.find(unionTarget.types, function (target) { + if (target.flags & 131072 /* Object */) { + var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); + if (overlapObjFlags & 4 /* Reference */) { + return source.target === target.target; + } + if (overlapObjFlags & 16 /* Anonymous */) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -39008,9 +40081,8 @@ var ts; var related = relation.get(id); if (related !== undefined) { if (reportErrors && related === 2 /* Failed */) { - // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported - // failure and continue computing the relation such that errors get reported. - relation.set(id, 3 /* FailedAndReported */); + // We are elaborating errors and the cached result is an unreported failure. The result will be reported + // as a failure, and should be updated as a reported failure by the bottom of this function. } else { return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; @@ -39285,10 +40357,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_1; - if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -39297,7 +40369,7 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } - var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source); + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { @@ -39320,6 +40392,33 @@ var ts; } } var result = -1 /* True */; + if (isTupleType(target)) { + var targetRestType = getRestTypeOfTupleType(target); + if (targetRestType) { + if (!isTupleType(source)) { + return 0 /* False */; + } + var sourceRestType = getRestTypeOfTupleType(source); + if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Rest_signatures_are_incompatible); + } + return 0 /* False */; + } + var targetCount = getTypeReferenceArity(target) - 1; + var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0); + for (var i = targetCount; i < sourceCount; i++) { + var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i); + } + return 0 /* False */; + } + result &= related; + } + } + } var properties = getPropertiesOfObjectType(target); for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { var targetProp = properties_3[_b]; @@ -39450,8 +40549,12 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); + var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { // An abstract constructor type is not assignable to a non-abstract constructor type @@ -39701,7 +40804,7 @@ var ts; return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -39841,20 +40944,26 @@ var ts; return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } function isMatchingSignature(source, target, partialMatch) { + var sourceParameterCount = getParameterCount(source); + var targetParameterCount = getParameterCount(target); + var sourceMinArgumentCount = getMinArgumentCount(source); + var targetMinArgumentCount = getMinArgumentCount(target); + var sourceHasRestParameter = hasEffectiveRestParameter(source); + var targetHasRestParameter = hasEffectiveRestParameter(target); // A source signature matches a target signature if the two signatures have the same number of required, // optional, and rest parameters. - if (source.parameters.length === target.parameters.length && - source.minArgumentCount === target.minArgumentCount && - source.hasRestParameter === target.hasRestParameter) { + if (sourceParameterCount === targetParameterCount && + sourceMinArgumentCount === targetMinArgumentCount && + sourceHasRestParameter === targetHasRestParameter) { return true; } // A source signature partially matches a target signature if the target signature has no fewer required // parameters and no more overall parameters than the source signature (where a signature with a rest // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + var sourceRestCount = sourceHasRestParameter ? 1 : 0; + var targetRestCount = targetHasRestParameter ? 1 : 0; + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { return true; } return false; @@ -39896,10 +41005,10 @@ var ts; } } } - var targetLen = target.parameters.length; + var targetLen = getParameterCount(target); for (var i = 0; i < targetLen; i++) { - var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); - var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); + var s = getTypeAtPosition(source, i); + var t = getTypeAtPosition(target, i); var related = compareTypes(s, t); if (!related) { return 0 /* False */; @@ -39919,9 +41028,6 @@ var ts; function compareTypePredicatesIdentical(source, target, compareTypes) { return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); } - function isRestParameterIndex(signature, parameterIndex) { - return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; - } function literalTypesWithSameBaseType(types) { var commonBaseType; for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { @@ -39960,6 +41066,9 @@ var ts; function isArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray @@ -39971,7 +41080,12 @@ var ts; return elementType === undefinedWideningType || elementType === implicitNeverType; } function isTupleLikeType(type) { - return !!getPropertyOfType(type, "0"); + return isTupleType(type) || !!getPropertyOfType(type, "0"); + } + function getTupleElementType(type, index) { + return isTupleType(type) ? + index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : + getTypeOfPropertyOfType(type, "" + index); } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -40018,6 +41132,12 @@ var ts; function isTupleType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); } + function getRestTypeOfTupleType(type) { + return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; + } + function getLengthOfTupleType(type) { + return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); + } function getFalsyFlagsOfTypes(types) { var result = 0; for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { @@ -40077,7 +41197,7 @@ var ts; if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); } - return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higherorder behavior + return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -40131,7 +41251,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; - regularNew.objectFlags |= 128 /* ObjectLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; } @@ -40178,14 +41298,6 @@ var ts; // widen accessor based properties here. return prop; } - if (prop.flags & 67108864 /* JSContainer */) { - var node = prop.declarations && ts.first(prop.declarations); - var init = ts.getAssignedJavascriptInitializer(node); - if (init && init.kind !== 184 /* ObjectLiteralExpression */) { - // for JS special declarations, the only kind of initializer that will widen is object literals - return prop; - } - } var original = getTypeOfSymbol(prop); var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); var widened = getWidenedTypeWithContext(original, propContext); @@ -40217,7 +41329,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); - return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); @@ -40298,7 +41412,7 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; @@ -40308,23 +41422,23 @@ var ts; ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 182 /* BindingElement */: + case 184 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 177 /* MappedType */: + case 179 /* MappedType */: error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); return; default: @@ -40341,24 +41455,22 @@ var ts; } } function forEachMatchingParameterType(source, target, callback) { - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var count; - if (source.hasRestParameter && target.hasRestParameter) { - count = Math.max(sourceMax, targetMax); - } - else if (source.hasRestParameter) { - count = targetMax; - } - else if (target.hasRestParameter) { - count = sourceMax; - } - else { - count = Math.min(sourceMax, targetMax); - } - for (var i = 0; i < count; i++) { + var sourceCount = getParameterCount(source); + var targetCount = getParameterCount(target); + var sourceHasRest = hasEffectiveRestParameter(source); + var targetHasRest = hasEffectiveRestParameter(target); + var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : + sourceHasRest ? targetCount : + targetHasRest ? sourceCount : + Math.min(sourceCount, targetCount); + var targetGenericRestType = getGenericRestType(target); + var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } + if (targetGenericRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); @@ -40469,6 +41581,22 @@ var ts; return undefined; } } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; @@ -40497,10 +41625,14 @@ var ts; } return undefined; } + function tupleTypesDefinitelyUnrelated(source, target) { + return target.target.minLength > source.target.minLength || + !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source)); + } function typesDefinitelyUnrelated(source, target) { - // Two tuple types with different arity are definitely unrelated. + // Two tuple types with incompatible arities are definitely unrelated. // Two object types that each have a property that is unmatched in the other are definitely unrelated. - return isTupleType(source) && isTupleType(target) && getTypeReferenceArity(source) !== getTypeReferenceArity(target) || + return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); } function getTypeFromInference(inference) { @@ -40783,12 +41915,33 @@ var ts; } } function inferFromProperties(source, target) { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + if (isTupleType(source) && isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + } + else { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } } } } @@ -40903,17 +42056,14 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + if (inference.contraCandidates) { + // If we have contravariant inferences we find the best common subtype and treat + // that as a single covariant candidate. + inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); + inference.contraCandidates = undefined; + } if (inference.candidates) { inferredType = getCovariantInference(inference, context, signature); - // If we have inferred 'never' but have contravariant candidates. To get a more specific type we - // infer from the contravariant candidates instead. - if (inferredType.flags & 32768 /* Never */ && inference.contraCandidates) { - inferredType = getContravariantInference(inference); - } - } - else if (inference.contraCandidates) { - // We only have contravariant inferences, infer the best common subtype of those - inferredType = getContravariantInference(inference); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -40990,13 +42140,13 @@ var ts; if (node.kind === 99 /* ThisKeyword */) { return "0"; } - if (node.kind === 185 /* PropertyAccessExpression */) { + if (node.kind === 187 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + ts.idText(node.name); } - if (node.kind === 182 /* BindingElement */) { + if (node.kind === 184 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 182 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 184 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -41005,13 +42155,13 @@ var ts; } function getBindingElementNameText(element) { var parent = element.parent; - if (parent.kind === 180 /* ObjectBindingPattern */) { + if (parent.kind === 182 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { case 71 /* Identifier */: return ts.idText(name); case 147 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; @@ -41028,34 +42178,40 @@ var ts; switch (source.kind) { case 71 /* Identifier */: return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 232 /* VariableDeclaration */ || target.kind === 182 /* BindingElement */) && + (target.kind === 235 /* VariableDeclaration */ || target.kind === 184 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 99 /* ThisKeyword */: return target.kind === 99 /* ThisKeyword */; case 97 /* SuperKeyword */: return target.kind === 97 /* SuperKeyword */; - case 185 /* PropertyAccessExpression */: - return target.kind === 185 /* PropertyAccessExpression */ && - source.name.escapedText === target.name.escapedText && + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 182 /* BindingElement */: - if (target.kind !== 185 /* PropertyAccessExpression */) + case 184 /* BindingElement */: + if (target.kind !== 187 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 182 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 184 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 232 /* VariableDeclaration */) { + if (source.parent.parent.kind === 235 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; return !!maybeId && isMatchingReference(maybeId, t.expression); } } return false; } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } function containsMatchingReference(source, target) { - while (source.kind === 185 /* PropertyAccessExpression */) { + while (source.kind === 187 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -41068,7 +42224,7 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 185 /* PropertyAccessExpression */ && + return target.kind === 187 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } @@ -41076,7 +42232,7 @@ var ts; if (expr.kind === 71 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 185 /* PropertyAccessExpression */) { + if (expr.kind === 187 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } @@ -41120,7 +42276,7 @@ var ts; } } } - if (callExpression.expression.kind === 185 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -41133,18 +42289,6 @@ var ts; } return flow.id; } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 262144 /* Union */)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -41153,7 +42297,7 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); if (!(reducedType.flags & 32768 /* Never */)) { return reducedType; } @@ -41246,7 +42390,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || + return isTupleLikeType(type) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -41254,15 +42398,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 183 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 270 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 185 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 273 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 200 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 222 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 225 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -41279,21 +42423,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return stringType; - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 194 /* DeleteExpression */: + case 196 /* DeleteExpression */: return undefinedType; - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 204 /* SpreadElement */: + case 206 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -41301,7 +42445,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 180 /* ObjectBindingPattern */ ? + var type = pattern.kind === 182 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -41319,35 +42463,35 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 221 /* ForInStatement */) { + if (node.parent.parent.kind === 224 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 222 /* ForOfStatement */) { + if (node.parent.parent.kind === 225 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 232 /* VariableDeclaration */ ? + return node.kind === 235 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 232 /* VariableDeclaration */ || node.kind === 182 /* BindingElement */ ? + return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : getAssignedType(node); } function isEmptyArrayAssignment(node) { - return node.kind === 232 /* VariableDeclaration */ && node.initializer && + return node.kind === 235 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 182 /* BindingElement */ && node.parent.kind === 200 /* BinaryExpression */ && + node.kind !== 184 /* BindingElement */ && node.parent.kind === 202 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: return getReferenceCandidate(node.left); @@ -41359,13 +42503,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 191 /* ParenthesizedExpression */ || - parent.kind === 200 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 200 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 193 /* ParenthesizedExpression */ || + parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || + parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 266 /* CaseClause */) { + if (clause.kind === 269 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -41409,7 +42553,7 @@ var ts; if (type.flags & 262144 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfUnitTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); } return f(type) ? type : neverType; } @@ -41528,11 +42672,11 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 185 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 187 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 186 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 187 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 189 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 188 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 200 /* BinaryExpression */ && + parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -41580,7 +42724,7 @@ var ts; // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent && reference.parent.kind === 209 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) { + if (reference.parent && reference.parent.kind === 211 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) { return declaredType; } return resultType; @@ -41651,7 +42795,10 @@ var ts; 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 !== 185 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + if (container && container !== flowContainer && + reference.kind !== 187 /* PropertyAccessExpression */ && + reference.kind !== 188 /* ElementAccessExpression */ && + reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -41707,7 +42854,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 187 /* CallExpression */ ? + var expr = node.kind === 189 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -41715,7 +42862,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 187 /* CallExpression */) { + if (node.kind === 189 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -41880,13 +43027,22 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 185 /* PropertyAccessExpression */ && - computedType.flags & 262144 /* Union */ && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(computedType, expr.name.escapedText); + if (!(computedType.flags & 262144 /* Union */) || + expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.escapedText; + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); @@ -41931,10 +43087,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 195 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + if (left_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 195 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + if (right_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -42149,7 +43305,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 186 /* ElementAccessExpression */ || invokedExpression.kind === 185 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 188 /* ElementAccessExpression */ || invokedExpression.kind === 187 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -42169,15 +43325,16 @@ var ts; case 71 /* Identifier */: case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 187 /* CallExpression */: + case 189 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: if (expr.operator === 51 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -42213,8 +43370,8 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 240 /* ModuleBlock */ || - node.kind === 274 /* SourceFile */ || + node.kind === 243 /* ModuleBlock */ || + node.kind === 277 /* SourceFile */ || node.kind === 152 /* PropertyDeclaration */; }); } @@ -42260,10 +43417,10 @@ var ts; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 185 /* PropertyAccessExpression */ || - parent.kind === 187 /* CallExpression */ && parent.expression === node || - parent.kind === 186 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 182 /* BindingElement */ && parent.name === node && !!parent.initializer; + return parent.kind === 187 /* PropertyAccessExpression */ || + parent.kind === 189 /* CallExpression */ && parent.expression === node || + parent.kind === 188 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 184 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 14745600 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576 /* Nullable */); @@ -42297,7 +43454,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 193 /* ArrowFunction */) { + if (container.kind === 195 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -42318,7 +43475,7 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 235 /* ClassDeclaration */ + if (declaration.kind === 238 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -42330,12 +43487,12 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 205 /* ClassExpression */) { + else if (declaration.kind === 207 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 274 /* SourceFile */) { + while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; @@ -42385,23 +43542,24 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; - var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 192 /* FunctionExpression */ || - flowContainer.kind === 193 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 194 /* FunctionExpression */ || + flowContainer.kind === 195 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || - isInTypeQuery(node) || node.parent.kind === 252 /* ExportSpecifier */) || - node.parent.kind === 209 /* NonNullExpression */ || - declaration.kind === 232 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || + node.parent.kind === 211 /* NonNullExpression */ || + declaration.kind === 235 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 4194304 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -42432,7 +43590,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 269 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 272 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -42457,8 +43615,8 @@ var ts; } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. - if (container.kind === 220 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 233 /* VariableDeclarationList */).parent === container && + if (container.kind === 223 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; } @@ -42472,7 +43630,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 191 /* ParenthesizedExpression */) { + while (current.parent.kind === 193 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -42480,7 +43638,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 198 /* PrefixUnaryExpression */ || current.parent.kind === 199 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 200 /* PrefixUnaryExpression */ || current.parent.kind === 201 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; } @@ -42538,7 +43696,7 @@ var ts; } function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); // If a containing class does not have extends clause or the class extends null // skip checking whether super statement is called before "this" accessing. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { @@ -42560,22 +43718,21 @@ var ts; // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); - var needToCaptureLexicalThis = false; + var capturedByArrowFunction = false; if (container.kind === 155 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 193 /* ArrowFunction */) { + if (container.kind === 195 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); - // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); + capturedByArrowFunction = true; } switch (container.kind) { - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; @@ -42596,13 +43753,16 @@ var ts; error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } - if (needToCaptureLexicalThis) { + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { captureLexicalThis(node, container); } var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); } return type || anyType; } @@ -42611,10 +43771,10 @@ var ts; if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. Check if it's the RHS - // of a x.prototype.y = function [name]() { .... } - if (container.kind === 192 /* FunctionExpression */ && - container.parent.kind === 200 /* BinaryExpression */ && + // If this is a function in a JS file, it might be a class method. + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 202 /* BinaryExpression */ && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') var className = container.parent // x.prototype.y = f @@ -42626,6 +43786,17 @@ var ts; return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); } } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJavascriptClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return getFlowTypeOfReference(node, thisType); @@ -42645,25 +43816,29 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 284 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && - jsDocFunctionType.parameters[0].name.escapedText === "this") { + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } + var thisTag = ts.getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } } function isInConstructorArgumentInitializer(node, constructorDecl) { return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 187 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 189 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 193 /* ArrowFunction */) { + while (container && container.kind === 195 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -42683,7 +43858,7 @@ var ts; else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 184 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -42771,7 +43946,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 184 /* ObjectLiteralExpression */) { + if (container.parent.kind === 186 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -42783,7 +43958,7 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } @@ -42815,7 +43990,7 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 184 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { return container.kind === 154 /* MethodDeclaration */ || container.kind === 153 /* MethodSignature */ || @@ -42839,8 +44014,8 @@ var ts; function getContainingObjectLiteral(func) { return (func.kind === 154 /* MethodDeclaration */ || func.kind === 156 /* GetAccessor */ || - func.kind === 157 /* SetAccessor */) && func.parent.kind === 184 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 192 /* FunctionExpression */ && func.parent.kind === 270 /* PropertyAssignment */ ? func.parent.parent : + func.kind === 157 /* SetAccessor */) && func.parent.kind === 186 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 194 /* FunctionExpression */ && func.parent.kind === 273 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -42852,7 +44027,7 @@ var ts; }); } function getContextualThisParameterType(func) { - if (func.kind === 193 /* ArrowFunction */) { + if (func.kind === 195 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -42879,7 +44054,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 270 /* PropertyAssignment */) { + if (literal.parent.kind !== 273 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -42893,9 +44068,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 200 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { var target = parent.left; - if (target.kind === 185 /* PropertyAccessExpression */ || target.kind === 186 /* ElementAccessExpression */) { + if (target.kind === 187 /* PropertyAccessExpression */ || target.kind === 188 /* ElementAccessExpression */) { 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)) { @@ -42918,41 +44093,26 @@ var ts; } var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { + var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + var type = indexOfParameter < args.length ? + getWidenedLiteralType(checkExpression(args[indexOfParameter])) : parameter.initializer ? undefined : undefinedWideningType; links.resolvedSignature = cached; return type; } var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - // If last parameter is contextually rest parameter get its type - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.last(contextualSignature.parameters)); - } + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); } } // In a variable, parameter or property declaration with a type annotation, @@ -42982,7 +44142,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 182 /* BindingElement */) { + if (parentDeclaration.kind !== 184 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -43038,10 +44198,9 @@ var ts; function getContextualReturnType(functionDecl) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.kind === 155 /* Constructor */ || - ts.getEffectiveReturnTypeNode(functionDecl) || - isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature @@ -43064,7 +44223,7 @@ var ts; return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 189 /* TaggedTemplateExpression */) { + if (template.parent.kind === 191 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -43090,30 +44249,58 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments to avoid circularity. + // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function isContextSensitiveAssignment(binaryExpression) { var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); switch (kind) { case 0 /* None */: return true; case 5 /* Property */: - // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. - // See `bindStaticPropertyAssignment` in `binder.ts`. - return !binaryExpression.left.symbol; case 1 /* ExportsProperty */: - case 2 /* ModuleExports */: + case 6 /* Prototype */: case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + if (ts.isInJavaScriptFile(decl)) { + return !!ts.getJSDocTypeTag(decl); + } + else if (ts.isIdentifier(binaryExpression.left.expression)) { + var id = binaryExpression.left.expression; + var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); + return !ts.isFunctionSymbol(parentSymbol); + } + return true; + } case 4 /* ThisProperty */: - case 6 /* Prototype */: - return false; + case 2 /* ModuleExports */: + return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); default: return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - var prop = t.flags & 917504 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; - return prop ? getTypeOfSymbol(prop) : undefined; + if (t.flags & 917504 /* StructuredType */) { + var prop = getPropertyOfType(t, name); + if (prop) { + return getTypeOfSymbol(prop); + } + if (isTupleType(t)) { + var restType = getRestTypeOfTupleType(t); + if (restType && isNumericLiteralName(name) && +name >= 0) { + return restType; + } + } + } + return undefined; }, /*noReductions*/ true); } function getIndexTypeOfContextualType(type, kind) { @@ -43142,8 +44329,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_1 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_1); + var symbolName_3 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); if (propertyType) { return propertyType; } @@ -43209,8 +44396,8 @@ var ts; case 95 /* NullKeyword */: case 71 /* Identifier */: return true; - case 185 /* PropertyAccessExpression */: - case 191 /* ParenthesizedExpression */: + case 187 /* PropertyAccessExpression */: + case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); } return false; @@ -43229,14 +44416,14 @@ var ts; var prop = _a[_i]; if (!prop.symbol) continue; - if (prop.kind !== 270 /* PropertyAssignment */) + if (prop.kind !== 273 /* PropertyAssignment */) continue; if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && checkTypeAssignableTo(discriminatingType, targetType, /*errorNode*/ undefined)) { + if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { if (match) { if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine @@ -43277,52 +44464,52 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: case 149 /* Parameter */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: - case 182 /* BindingElement */: + case 184 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 193 /* ArrowFunction */: - case 225 /* ReturnStatement */: + case 195 /* ArrowFunction */: + case 228 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 187 /* CallExpression */: - case 188 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 190 /* TypeAssertionExpression */: - case 208 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 270 /* PropertyAssignment */: - case 271 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 272 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 183 /* ArrayLiteralExpression */: { + case 185 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 211 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 202 /* TemplateExpression */); + case 214 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 204 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 191 /* ParenthesizedExpression */: { + case 193 /* 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 265 /* JsxExpression */: + case 268 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 262 /* JsxAttribute */: - case 264 /* JsxSpreadAttribute */: + case 265 /* JsxAttribute */: + case 267 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 257 /* JsxOpeningElement */: - case 256 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent); } return undefined; @@ -43396,6 +44583,7 @@ var ts; } function getJsxPropsTypeFromCallSignature(sig, context) { var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); if (intrinsicAttribs !== errorType) { propsType = intersectTypes(intrinsicAttribs, propsType); @@ -43406,8 +44594,24 @@ var ts; var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + var managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + if (ts.length(declaredManagedType.typeParameters) >= 2) { + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + return createTypeReference(declaredManagedType, args); + } + else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); + } + } + return attributesType; + } function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) { - var forcedLookupLocation = getJsxElementPropertiesName(getJsxNamespaceAt(context)); + var ns = getJsxNamespaceAt(context); + var forcedLookupLocation = getJsxElementPropertiesName(ns); var attributesType = forcedLookupLocation === undefined // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType) @@ -43423,7 +44627,8 @@ var ts; } return emptyObjectType; } - else if (isTypeAny(attributesType)) { + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { // Props is of type 'any' or unknown return attributesType; } @@ -43468,11 +44673,10 @@ var ts; if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { targetParameterCount--; } - var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; - return sourceLength < targetParameterCount; + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 192 /* FunctionExpression */ || node.kind === 193 /* ArrowFunction */; + return node.kind === 194 /* FunctionExpression */ || node.kind === 195 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -43492,16 +44696,11 @@ var ts; // union type of return types from these signatures function getContextualSignature(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type; - if (ts.isInJavaScriptFile(node)) { - var jsdoc = ts.getJSDocType(node); - if (jsdoc) { - type = getTypeFromTypeNode(jsdoc); - } - } - if (!type) { - type = getContextualTypeForFunctionLikeDeclaration(node); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; } + var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } @@ -43544,18 +44743,19 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 182 /* BindingElement */ && !!node.initializer) || - (node.kind === 200 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 184 /* BindingElement */ && !!node.initializer) || + (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } function checkArrayLiteral(node, checkMode) { var elements = node.elements; - var hasSpreadElement = false; + var elementCount = elements.length; + var hasNonEndingSpreadElement = false; var elementTypes = []; var inDestructuringPattern = ts.isAssignmentTarget(node); var contextualType = getApparentTypeOfContextualType(node); - for (var index = 0; index < elements.length; index++) { + for (var index = 0; index < elementCount; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 204 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 206 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -43580,13 +44780,17 @@ var ts; var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 204 /* SpreadElement */; + if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { + hasNonEndingSpreadElement = true; + } } - if (!hasSpreadElement) { + if (!hasNonEndingSpreadElement) { + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206 /* SpreadElement */; + var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". - if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); + if (inDestructuringPattern && minLength > 0) { + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } @@ -43594,28 +44798,30 @@ var ts; var pattern = contextualType.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 === 181 /* ArrayBindingPattern */ || pattern.kind === 183 /* ArrayLiteralExpression */)) { + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; - for (var i = elementTypes.length; i < patternElements.length; i++) { - var patternElement = patternElements[i]; - if (hasDefaultValue(patternElement)) { + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { elementTypes.push(contextualType.typeArguments[i]); } - else { - if (patternElement.kind !== 206 /* OmittedExpression */) { - error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } - if (elementTypes.length) { - return createTupleType(elementTypes); - } + return createTupleType(elementTypes, minLength, hasRestElement); } } + return getArrayLiteralType(elementTypes, 2 /* Subtype */); + } + function getArrayLiteralType(elementTypes, unionReduction) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, 2 /* Subtype */) : + getUnionType(elementTypes, unionReduction) : strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { @@ -43700,25 +44906,14 @@ var ts; var propagatedFlags = 33554432 /* FreshLiteral */; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 180 /* ObjectBindingPattern */ || contextualType.pattern.kind === 184 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); - var isJSObjectLiteral = !contextualType && isInJSFile; + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - if (isInJSFile) { - var decl = ts.getDeclarationOfJSInitializer(node); - if (decl) { - // a JS object literal whose declaration's symbol has exports is a JS namespace - var symbol = getSymbolOfNode(decl); - if (symbol && ts.hasEntries(symbol.exports)) { - propertiesTable = symbol.exports; - symbol.exports.forEach(function (s) { return propertiesArray.push(getMergedSymbol(s)); }); - return createObjectLiteralType(); - } - } - } propertiesTable = ts.createSymbolTable(); var offset = 0; for (var i = 0; i < node.properties.length; i++) { @@ -43726,11 +44921,11 @@ var ts; var member = getSymbolOfNode(memberDecl); var computedNameType = memberDecl.name && memberDecl.name.kind === 147 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 270 /* PropertyAssignment */ || - memberDecl.kind === 271 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 273 /* PropertyAssignment */ || + memberDecl.kind === 274 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 270 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : - memberDecl.kind === 271 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJSFile) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); @@ -43738,6 +44933,9 @@ var ts; checkTypeAssignableTo(type, jsDocType, memberDecl); type = jsDocType; } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } } typeFlags |= type.flags; var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? @@ -43751,8 +44949,8 @@ var ts; 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. - var isOptional = (memberDecl.kind === 270 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 271 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 273 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 274 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -43777,7 +44975,7 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 272 /* SpreadAssignment */) { + else if (memberDecl.kind === 275 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } @@ -43847,12 +45045,15 @@ var ts; } return createObjectLiteralType(); function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); result.objectFlags |= 128 /* ObjectLiteral */; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } @@ -43871,13 +45072,16 @@ var ts; type.flags & 131072 /* Object */ && !isGenericMappedType(type) || type.flags & 786432 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); } - function checkJsxSelfClosingElement(node, checkMode) { - checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node, 0 /* Normal */); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } - function checkJsxElement(node, checkMode) { + function checkJsxElementDeferred(node) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0 /* Normal */); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -43885,6 +45089,9 @@ var ts; else { checkExpression(node.closingElement.tagName); } + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } function checkJsxFragment(node, checkMode) { @@ -43907,16 +45114,7 @@ var ts; * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name */ function isJsxIntrinsicIdentifier(tagName) { - // TODO (yuisu): comment - switch (tagName.kind) { - case 185 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: - return false; - case 71 /* Identifier */: - return ts.isIntrinsicJsxName(tagName.escapedText); - default: - return ts.Debug.fail(); - } + return tagName.kind === 71 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); } function checkJsxAttribute(node, checkMode) { return node.initializer @@ -43959,7 +45157,7 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 264 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); @@ -43982,7 +45180,7 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 255 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 258 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -44143,12 +45341,24 @@ var ts; return getSignatureInstantiation(signature, args, isJavascript); } function getJsxNamespaceAt(location) { - var namespaceName = getJsxNamespace(location); - var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); - if (resolvedNamespace) { - var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); - if (candidate) { - return candidate; + var links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + if (links) { + links.jsxNamespace = false; + } } } // JSX global fallback @@ -44185,6 +45395,10 @@ var ts; } return undefined; } + function getJsxLibraryManagedAttributes(jsxNamespace) { + // JSX.LibraryManagedAttributes [symbol] + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all /// non-intrinsic elements' attributes type is 'any'), @@ -44226,7 +45440,7 @@ var ts; var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); @@ -44262,7 +45476,7 @@ var ts; if (jsxStatelessElementType) { // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); var result = void 0; var allMatchingAttributesType = void 0; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { @@ -44570,6 +45784,10 @@ var ts; } } } + else if (targetType.flags & 4194304 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } return false; } /** @@ -44591,7 +45809,7 @@ var ts; // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); + var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. @@ -44612,31 +45830,7 @@ var ts; } } else if (!isSourceAttributeTypeAssignableToTarget) { - // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span - if (ts.length(openingLikeElement.attributes.properties)) { - var reportedError = false; - var _loop_5 = function (prop) { - if (ts.isJsxSpreadAttribute(prop)) - return "continue"; - var name = ts.idText(prop.name); - var sourcePropType = getIndexedAccessType(sourceAttributesType, getLiteralType(name)); - var targetPropType = getIndexedAccessType(targetAttributesType, getLiteralType(name)); - var rootChain = function () { return ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Types_of_property_0_are_incompatible, name); }; - if (!checkTypeAssignableTo(sourcePropType, targetPropType, prop, /*headMessage*/ undefined, rootChain)) { - reportedError = true; - } - }; - for (var _b = 0, _c = openingLikeElement.attributes.properties; _b < _c.length; _b++) { - var prop = _c[_b]; - _loop_5(prop); - } - if (reportedError) { - return; - } - } - // Report fallback error on just the component name - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.tagName); + checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); } } function checkJsxExpression(node, checkMode) { @@ -44651,11 +45845,6 @@ var ts; return errorType; } } - // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized - // '.prototype' property as well as synthesized tuple index properties. - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 152 /* PropertyDeclaration */; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } @@ -44677,23 +45866,19 @@ var ts; * Check whether the requested property access is valid. * Returns true if node is a valid property access, and false otherwise. * @param node The node to be checked. - * @param left The left hand side of the property access (e.g.: the super in `super.foo`). - * @param type The type of left. - * @param prop The symbol for the right hand side of the property access. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, left, type, prop) { + function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 185 /* PropertyAccessExpression */ || node.kind === 232 /* VariableDeclaration */ ? - node.name : - node.kind === 179 /* ImportType */ ? - node : - node.right; + var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or // instance member variable initializer where this references a derived class instance, @@ -44740,7 +45925,7 @@ var ts; } // Property is known to be protected at this point // All protected properties of a supertype are accessible in a super access - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { return true; } // Find the first enclosing class that has the declaring classes of the protected constituents @@ -44759,7 +45944,7 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintFromTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { @@ -44780,10 +45965,7 @@ var ts; return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; } function symbolHasNonMethodDeclaration(symbol) { - return forEachProperty(symbol, function (prop) { - var propKind = getDeclarationKindFromSymbol(prop); - return propKind !== 154 /* MethodDeclaration */ && propKind !== 153 /* MethodSignature */; - }); + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); @@ -44829,6 +46011,9 @@ var ts; if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } @@ -44843,7 +46028,7 @@ var ts; checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); @@ -44855,7 +46040,7 @@ var ts; // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 185 /* PropertyAccessExpression */ || + if (node.kind !== 187 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 262144 /* Union */)) { return propType; @@ -44887,16 +46072,21 @@ var ts; if (!valueDeclaration) { return; } + var diagnosticMessage; + var declarationName = ts.idText(right); if (isInPropertyInitializer(node) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !isPropertyDeclaredInAncestorClass(prop)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.idText(right)); + diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 235 /* ClassDeclaration */ && + else if (valueDeclaration.kind === 238 /* ClassDeclaration */ && node.parent.kind !== 162 /* TypeReference */ && !(valueDeclaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.idText(right)); + diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializer(node) { @@ -44904,7 +46094,7 @@ var ts; switch (node.kind) { case 152 /* PropertyDeclaration */: return true; - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: @@ -44941,6 +46131,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; + var relatedInfo; if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; @@ -44950,26 +46141,44 @@ var ts; } } } - var promisedType = getPromisedTypeOfPromise(containingType); - if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - 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), suggestion); + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); } - function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 67216319 /* Value */); + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + } + function getSuggestionForNonexistentProperty(name, containingType) { + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); @@ -44979,10 +46188,17 @@ var ts; // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - return result && ts.symbolName(result); + return result; } - function getSuggestionForNonexistentModule(name, targetModule) { - var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); return suggestion && ts.symbolName(suggestion); } /** @@ -45025,16 +46241,16 @@ var ts; } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 185 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression, propertyName, getWidenedType(checkExpression(node.expression))); + case 187 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); case 146 /* QualifiedName */: - return isValidPropertyAccessWithType(node, node.left, propertyName, getWidenedType(checkExpression(node.left))); - case 179 /* ImportType */: - return isValidPropertyAccessWithType(node, node, propertyName, getTypeFromTypeNode(node)); + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); + case 181 /* ImportType */: + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 179 /* ImportType */ ? node : node.expression, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -45054,21 +46270,21 @@ var ts; inferTypes(context.inferences, actualThisType, signatureThisType); return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); } - function isValidPropertyAccessWithType(node, left, propertyName, type) { + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { if (type === errorType || isTypeAny(type)) { return true; } var prop = getPropertyOfType(type, propertyName); - return prop ? checkPropertyAccessibility(node, left, type, prop) + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 233 /* VariableDeclarationList */) { + if (initializer.kind === 236 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -45097,7 +46313,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 221 /* ForInStatement */ && + if (node.kind === 224 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -45115,7 +46331,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 188 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 190 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -45182,7 +46398,7 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 189 /* TaggedTemplateExpression */) { + if (node.kind === 191 /* TaggedTemplateExpression */) { checkExpression(node.template); } else if (node.kind !== 150 /* Decorator */) { @@ -45248,31 +46464,26 @@ var ts; result.splice(spliceIndex, 0, signature); } } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 206 /* SpreadElement */ || arg.kind === 213 /* SyntheticExpression */ && arg.isSpread); + } function getSpreadArgumentIndex(args) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg && arg.kind === 204 /* SpreadElement */) { - return i; - } - } - return -1; + return ts.findIndex(args, isSpreadArgument); } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call - var typeArguments; // Type arguments (undefined if none) var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } - if (node.kind === 189 /* TaggedTemplateExpression */) { + if (node.kind === 191 /* TaggedTemplateExpression */) { // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = node.typeArguments; - if (node.template.kind === 202 /* TemplateExpression */) { + if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -45288,35 +46499,29 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 188 /* NewExpression */); - return signature.minArgumentCount === 0; + ts.Debug.assert(node.kind === 190 /* NewExpression */); + return getMinArgumentCount(signature) === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } - if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { - return false; - } // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || - signature.minArgumentCount <= spreadArgIndex && spreadArgIndex < signature.parameters.length; + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); } // Too many arguments implies incorrect arity. - if (!signature.hasRestParameter && argCount > signature.parameters.length) { + if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { return false; } // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= signature.minArgumentCount; + var hasEnoughArguments = argCount >= getMinArgumentCount(signature); return callIsIncomplete || hasEnoughArguments; } function hasCorrectTypeArgumentArity(signature, typeArguments) { @@ -45341,9 +46546,10 @@ var ts; // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); - forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; + forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type - inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); + inferTypes(context.inferences, source, target); }); if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); @@ -45393,7 +46599,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, ts.isInJavaScriptFile(node))) : + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. @@ -45408,11 +46614,13 @@ var ts; } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. - var argCount = getEffectiveArgumentCount(node, args, signature); + var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); + var genericRestType = getGenericRestType(signature); + var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 206 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type @@ -45426,6 +46634,10 @@ var ts; inferTypes(context.inferences, argType, paramType); } } + if (genericRestType) { + var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); + inferTypes(context.inferences, spreadType, genericRestType); + } // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed // as we construct types for contextually typed parameters) @@ -45443,6 +46655,35 @@ var ts; } return getInferredTypes(context); } + function getSpreadArgumentType(node, args, index, argCount, restType, context) { + if (index >= argCount - 1) { + var arg = getEffectiveArgument(node, args, argCount - 1); + if (isSpreadArgument(arg)) { + // We are inferring from a spread expression in the last argument position, i.e. both the parameter + // and the argument are ...x forms. + return arg.kind === 213 /* SyntheticExpression */ ? + createArrayType(arg.type) : + checkExpressionWithContextualType(arg.expression, restType, context); + } + } + var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 /* Primitive */ | 1048576 /* Index */); + var types = []; + var spreadIndex = -1; + for (var i = index; i < argCount; i++) { + var argType = getEffectiveArgumentType(node, i); + if (!argType) { + argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; + } + } + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + } + return spreadIndex < 0 ? + createTupleType(types) : + createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); + } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; @@ -45502,7 +46743,7 @@ var ts; return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 188 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 190 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -45516,24 +46757,32 @@ var ts; } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; var argCount = getEffectiveArgumentCount(node, args, signature); + var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; + var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 206 /* OmittedExpression */) { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; + if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { + var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); + return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); + } + else { + // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) + var paramType = getTypeAtPosition(signature, i); + // If the effective argument type is undefined, there is no synthetic type for the argument. + // In that case, we should check the argument. + var argType = getEffectiveArgumentType(node, i) || + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + // Use argument expression as error location when reporting errors + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { + return false; + } } } } @@ -45543,9 +46792,9 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 187 /* CallExpression */) { + if (node.kind === 189 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); - if (callee.kind === 185 /* PropertyAccessExpression */ || callee.kind === 186 /* ElementAccessExpression */) { + if (callee.kind === 187 /* PropertyAccessExpression */ || callee.kind === 188 /* ElementAccessExpression */) { return callee.expression; } } @@ -45560,15 +46809,15 @@ var ts; * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 189 /* TaggedTemplateExpression */) { + if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_1 = [undefined]; // TODO: GH#18217 - if (template.kind === 202 /* TemplateExpression */) { + var args_4 = [undefined]; // TODO: GH#18217 + if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { - args_1.push(span.expression); + args_4.push(span.expression); }); } - return args_1; + return args_4; } else if (node.kind === 150 /* Decorator */) { // For a decorator, we return undefined as we will determine @@ -45580,7 +46829,28 @@ var ts; return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } else { - return node.arguments || ts.emptyArray; + var args = node.arguments || ts.emptyArray; + var length_4 = args.length; + if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length_4 - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { + var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); + arg.parent = spreadArgument_1; + arg.type = t; + arg.isSpread = i === restIndex_2; + return arg; + }); + return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); + } + } + return args; } } /** @@ -45599,8 +46869,8 @@ var ts; function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 150 /* Decorator */) { switch (node.parent.kind) { - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; case 152 /* PropertyDeclaration */: @@ -45645,7 +46915,7 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 235 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); @@ -45690,7 +46960,7 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 235 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return errorType; } @@ -45745,7 +47015,7 @@ var ts; function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a parameter decorator - if (node.kind === 235 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return errorType; } @@ -45762,7 +47032,7 @@ var ts; node.kind === 157 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - var propertyType = getTypeOfNode(node); // TODO: GH#18217 + var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); @@ -45794,7 +47064,7 @@ var ts; if (node.kind === 150 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 189 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { return getGlobalTemplateStringsArrayType(); } // This is not a synthetic argument, so we return 'undefined' @@ -45807,7 +47077,7 @@ var ts; function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 189 /* TaggedTemplateExpression */)) { + (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -45820,7 +47090,7 @@ var ts; // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 189 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -45828,19 +47098,55 @@ var ts; return arg; } } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + min = Math.min(min, minCount); + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } var paramCount = min === max ? min : min + "-" + max; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 189 /* TaggedTemplateExpression */; + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { + var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; var isDecorator = node.kind === 150 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; @@ -45911,11 +47217,12 @@ var ts; // foo(0); // var candidateForArgumentError; + var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 187 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -45951,73 +47258,30 @@ var ts; // an error, we don't need to exclude any arguments, although it would cause no harm to do so. checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { - var min_1 = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; - min_1 = Math.min(min_1, sig.minArgumentCount); - max = Math.max(max, sig.parameters.length); - } - var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - var paramCount = hasRestParameter_1 ? min_1 : - min_1 < max ? min_1 + "-" + max : - min_1; - var argCount = args.length; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - ts.Diagnostics.Expected_0_arguments_but_got_1; - diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + diagnostics.add(getArgumentArityError(node, signatures, args)); } else if (fallbackError) { diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } - // No signature was applicable. We have already reported the errors for the invalid signature. - // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. - // Pick the longest signature. This way we can get a contextual type for cases like: - // declare function f(a: { xa: number; xb: number; }, b: number); - // f({ | - // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: - // declare function f(k: keyof T); - // f(" - if (!produceDiagnostics) { - ts.Debug.assert(candidates.length > 0); // Else would have exited above. - var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); - var candidate = candidates[bestIndex]; - var typeParameters = candidate.typeParameters; - if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); // TODO: GH#18217 - while (typeArguments_1.length > typeParameters.length) { - typeArguments_1.pop(); - } - while (typeArguments_1.length < typeParameters.length) { - typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); - } - var instantiated = createSignatureInstantiation(candidate, typeArguments_1); - candidates[bestIndex] = instantiated; - return instantiated; - } - return candidate; - } - return resolveErrorCall(node); + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -46028,7 +47292,7 @@ var ts; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; @@ -46054,6 +47318,12 @@ var ts; } var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = candidate; + break; + } } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; @@ -46075,35 +47345,120 @@ var ts; return undefined; } } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_6 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_6(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments); + candidates[bestIndex] = instantiated; + return instantiated; + } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; var maxParams = -1; for (var i = 0; i < candidates.length; i++) { var candidate = candidates[i]; - if (candidate.hasRestParameter || candidate.parameters.length >= argsCount) { + var paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { return i; } - if (candidate.parameters.length > maxParams) { - maxParams = candidate.parameters.length; + if (paramCount > maxParams) { + maxParams = paramCount; maxParamsIndex = i; } } return maxParamsIndex; } - function resolveCallExpression(node, candidatesOutArray) { + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { - ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } return anySignature; } if (superType !== errorType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); + var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); } } return resolveUntypedCall(node); @@ -46146,7 +47501,12 @@ var ts; } return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * TS 1.0 spec: 4.12 @@ -46158,7 +47518,7 @@ var ts; return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } - function resolveNewExpression(node, candidatesOutArray) { + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { @@ -46206,7 +47566,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray); + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -46214,8 +47574,8 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } if (getThisTypeOfSignature(signature) === voidType) { @@ -46226,6 +47586,38 @@ var ts; invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 524288 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } function isConstructorAccessible(node, signature) { if (!signature || !signature.declaration) { return true; @@ -46241,16 +47633,10 @@ var ts; // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); - if (containingClass) { + if (containingClass && modifiers & 16 /* Protected */) { var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; } } if (modifiers & 8 /* Private */) { @@ -46264,12 +47650,11 @@ var ts; return true; } function invocationError(node, apparentType, kind) { - error(node, kind === 0 /* Call */ + invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); - invocationErrorRecovery(apparentType, kind); + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); } - function invocationErrorRecovery(apparentType, kind) { + function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { return; } @@ -46280,10 +47665,10 @@ var ts; var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); if (!sigs || !sigs.length) return; - error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); if (apparentType === errorType) { @@ -46299,15 +47684,15 @@ var ts; invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; case 149 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; @@ -46324,7 +47709,7 @@ var ts; /** * Resolves a decorator as if it were a call expression. */ - function resolveDecorator(node, candidatesOutArray) { + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); if (apparentType === errorType) { @@ -46344,11 +47729,12 @@ var ts; if (!callSignatures.length) { var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - invocationErrorRecovery(apparentType, 0 /* Call */); + var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo); + diagnostics.add(diag); + invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -46372,30 +47758,30 @@ var ts; * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; * the function will fill it up with appropriate candidate signatures */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); } return undefined; } - function resolveSignature(node, candidatesOutArray) { + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { - case 187 /* CallExpression */: - return resolveCallExpression(node, candidatesOutArray); - case 188 /* NewExpression */: - return resolveNewExpression(node, candidatesOutArray); - case 189 /* TaggedTemplateExpression */: - return resolveTaggedTemplateExpression(node, candidatesOutArray); + case 189 /* CallExpression */: + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); + case 190 /* NewExpression */: + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); + case 191 /* TaggedTemplateExpression */: + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); case 150 /* Decorator */: - return resolveDecorator(node, candidatesOutArray); - case 257 /* JsxOpeningElement */: - case 256 /* JsxSelfClosingElement */: + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: // This code-path is called by language service var exprTypes = checkExpression(node.tagName); return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); if (sfcResult && sfcResult !== unknownSignature) { return sfcResult; } @@ -46415,7 +47801,8 @@ var ts; * the function will fill it up with appropriate candidate signatures * @return a signature of the call-like expression or undefined if one can't be found */ - function getResolvedSignature(node, candidatesOutArray) { + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } var links = getNodeLinks(node); // If getResolvedSignature has already been called, we will have cached the resolvedSignature. // However, it is possible that either candidatesOutArray was not passed in the first time, @@ -46426,7 +47813,7 @@ var ts; return cached; } links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); // If signature resolution originated in control flow type analysis (for example to compute the // assigned type in a flow assignment) we don't cache the result as it may be based on temporary // types from the control flow analysis. @@ -46437,7 +47824,7 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavaScriptConstructor(node) { + function isJavascriptConstructor(node) { if (node && ts.isInJavaScriptFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) @@ -46450,14 +47837,21 @@ var ts; } return false; } - function getJavaScriptClassType(symbol) { + function isJavascriptConstructorType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJavascriptClassType(symbol) { var inferred; - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -46467,7 +47861,8 @@ var ts; function getAssignedClassType(symbol) { var decl = symbol.valueDeclaration; var assignmentSymbol = decl && decl.parent && - (ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || + ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); if (assignmentSymbol) { var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); @@ -46481,7 +47876,7 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 185 /* PropertyAccessExpression */) { + while (parent && parent.kind === 187 /* PropertyAccessExpression */) { parent = parent.parent; } if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58 /* EqualsToken */) { @@ -46513,7 +47908,7 @@ var ts; if (node.expression.kind === 97 /* SuperKeyword */) { return voidType; } - if (node.kind === 188 /* NewExpression */) { + if (node.kind === 190 /* NewExpression */) { var declaration = signature.declaration; if (declaration && declaration.kind !== 155 /* Constructor */ && @@ -46529,7 +47924,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavaScriptClassType(funcSymbol); + var type = funcSymbol && getJavascriptClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -46555,7 +47950,8 @@ var ts; if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { - jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; } } } @@ -46587,7 +47983,7 @@ var ts; } var specifier = node.arguments[0]; var specifierType = checkExpressionCached(specifier); - // Even though multiple arugments is grammatically incorrect, type-check extra arguments for completion + // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } @@ -46644,9 +48040,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 234 /* FunctionDeclaration */ + ? 237 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 232 /* VariableDeclaration */ + ? 235 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -46672,7 +48068,7 @@ var ts; if (produceDiagnostics && targetType !== errorType) { var widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); } } return targetType; @@ -46724,10 +48120,107 @@ var ts; } return type; } + function getParameterNameAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + var restParameter = signature.parameters[paramCount] || unknownSymbol; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var associatedNames = restType.target.associatedNames; + var index = pos - paramCount; + return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + } + return restParameter.escapedName; + } function getTypeAtPosition(signature, pos) { - return signature.hasRestParameter ? - pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : - pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[paramCount]); + if (isTupleType(restType)) { + if (pos - paramCount < getLengthOfTupleType(restType)) { + return restType.typeArguments[pos - paramCount]; + } + return getRestTypeOfTupleType(restType); + } + return getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getRestTypeAtPosition(source, pos) { + var paramCount = getParameterCount(source); + var hasRest = hasEffectiveRestParameter(source); + if (hasRest && pos === paramCount - 1) { + var genericRestType = getGenericRestType(source); + if (genericRestType) { + return genericRestType; + } + } + var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var types = []; + var names = []; + for (var i = start; i < paramCount; i++) { + types.push(getTypeAtPosition(source, i)); + names.push(getParameterNameAtPosition(source, i)); + } + var minArgumentCount = getMinArgumentCount(source); + var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + return createTupleType(types, minLength, hasRest, names); + } + function getTypeOfRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + return getRestTypeOfTupleType(restType); + } + return restType; + } + return undefined; + } + function getParameterCount(signature) { + var length = signature.parameters.length; + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[length - 1]); + if (isTupleType(restType)) { + return length + (restType.typeArguments || ts.emptyArray).length - 1; + } + } + return length; + } + function getMinArgumentCount(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + var minLength = restType.target.minLength; + if (minLength > 0) { + return signature.parameters.length - 1 + minLength; + } + } + } + return signature.minArgumentCount; + } + function getGenericRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (restType.flags & 15794176 /* Instantiable */) { + return restType; + } + } + return undefined; + } + function hasEffectiveRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || restType.target.hasRestElement; + } + return false; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -46766,11 +48259,11 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + if (signature.hasRestParameter) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { - var contextualParameterType = getTypeOfSymbol(ts.last(context.parameters)); + var contextualParameterType = getRestTypeAtPosition(context, len); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } @@ -46835,7 +48328,7 @@ var ts; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 213 /* Block */) { + if (func.body.kind !== 216 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -46924,7 +48417,7 @@ var ts; } function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { var errorNode = node.expression || node; - var expressionType = node.expression ? checkExpressionCached(node.expression, checkMode) : undefinedWideningType; + var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType; // A `yield*` expression effectively yields everything that its operand yields var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken @@ -46949,7 +48442,7 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - if (ts.some(func.body.statements, function (statement) { return statement.kind === 227 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; @@ -46984,7 +48477,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -46992,11 +48485,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; case 154 /* MethodDeclaration */: - return func.parent.kind === 184 /* ObjectLiteralExpression */; + return func.parent.kind === 186 /* ObjectLiteralExpression */; default: return false; } @@ -47015,12 +48508,12 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 3 /* AnyOrUnknown */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 213 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 216 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; @@ -47056,11 +48549,21 @@ var ts; ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + } return anyFunctionType; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 192 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 194 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); @@ -47087,7 +48590,7 @@ var ts; contextualSignature : instantiateSignature(contextualSignature, contextualMapper); assignContextualParameterTypes(signature, instantiatedContextualSignature); } - if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, checkMode); if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; @@ -47100,20 +48603,21 @@ var ts; } return type; } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - var returnOrPromisedType = returnTypeNode && - ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : // Async function - getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { - if (!returnTypeNode) { + if (!ts.getEffectiveReturnTypeNode(node)) { // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors // we need. An example is the noImplicitAny errors resulting from widening the return expression // of a function. Because checking of function expression bodies is deferred, there was never an @@ -47121,7 +48625,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 213 /* Block */) { + if (node.body.kind === 216 /* Block */) { checkSourceElement(node.body); } else { @@ -47134,10 +48638,10 @@ var ts; if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); } else { // Normal function - checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); + checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); } } } @@ -47167,7 +48671,7 @@ var ts; if (isReadonlySymbol(symbol)) { // Allow assignments to readonly properties within constructors of the same class declaration. if (symbol.flags & 4 /* Property */ && - (expr.kind === 185 /* PropertyAccessExpression */ || expr.kind === 186 /* ElementAccessExpression */) && + (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) && expr.expression.kind === 99 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); @@ -47177,20 +48681,20 @@ var ts; // If func.parent is a class and symbol is a (readonly) property of that class, or // if func is a constructor and symbol is a (readonly) parameter property declared in it, // then symbol is writeable here. - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 185 /* PropertyAccessExpression */ || expr.kind === 186 /* ElementAccessExpression */) { + if (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); if (node.kind === 71 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return !!declaration && declaration.kind === 246 /* NamespaceImport */; + return !!declaration && declaration.kind === 249 /* NamespaceImport */; } } } @@ -47199,7 +48703,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 185 /* PropertyAccessExpression */ && node.kind !== 186 /* ElementAccessExpression */) { + if (node.kind !== 71 /* Identifier */ && node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -47208,7 +48712,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 185 /* PropertyAccessExpression */ && expr.kind !== 186 /* ElementAccessExpression */) { + if (expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -47263,6 +48767,7 @@ var ts; } return numberType; case 51 /* ExclamationToken */: + checkTruthinessExpression(node.operand); var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); return facts === 1048576 /* Truthy */ ? falseType : facts === 2097152 /* Falsy */ ? trueType : @@ -47372,20 +48877,21 @@ var ts; } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType) { + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { var properties = node.properties; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; } /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 270 /* PropertyAssignment */ || property.kind === 271 /* ShorthandPropertyAssignment */) { + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } + if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { var name = property.name; if (name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(name); @@ -47393,26 +48899,16 @@ var ts; if (isComputedNonLiteralName(name)) { return undefined; } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || - getIndexTypeOfType(objectLiteralType, 0 /* String */); + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { - if (property.kind === 271 /* ShorthandPropertyAssignment */) { - return checkDestructuringAssignment(property, type); - } - else { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.initializer, type); - } + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 272 /* SpreadAssignment */) { + else if (property.kind === 275 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } @@ -47430,6 +48926,23 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -47447,27 +48960,23 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 206 /* OmittedExpression */) { - if (element.kind !== 204 /* SpreadElement */) { + if (element.kind !== 208 /* OmittedExpression */) { + if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; - var type = isTypeAny(sourceType) - ? sourceType - : isTupleLikeType(sourceType) - ? getTypeOfPropertyOfType(sourceType, propName) - : elementType; + var type = isTypeAny(sourceType) ? sourceType : + isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); } + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } else { - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); } } else { @@ -47476,21 +48985,24 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 200 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 202 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); + var type = isTupleType(sourceType) ? + getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } } return undefined; } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 271 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -47506,25 +49018,25 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 200 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 202 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 184 /* ObjectLiteralExpression */) { - return checkObjectLiteralAssignment(target, sourceType); + if (target.kind === 186 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 183 /* ArrayLiteralExpression */) { + if (target.kind === 185 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 272 /* SpreadAssignment */ ? + var error = target.parent.kind === 275 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { - checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); } return sourceType; } @@ -47542,35 +49054,35 @@ var ts; case 71 /* Identifier */: case 9 /* StringLiteral */: case 12 /* RegularExpressionLiteral */: - case 189 /* TaggedTemplateExpression */: - case 202 /* TemplateExpression */: + case 191 /* TaggedTemplateExpression */: + case 204 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 140 /* UndefinedKeyword */: - case 192 /* FunctionExpression */: - case 205 /* ClassExpression */: - case 193 /* ArrowFunction */: - case 183 /* ArrayLiteralExpression */: - case 184 /* ObjectLiteralExpression */: - case 195 /* TypeOfExpression */: - case 209 /* NonNullExpression */: - case 256 /* JsxSelfClosingElement */: - case 255 /* JsxElement */: + case 194 /* FunctionExpression */: + case 207 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 185 /* ArrayLiteralExpression */: + case 186 /* ObjectLiteralExpression */: + case 197 /* TypeOfExpression */: + case 211 /* NonNullExpression */: + case 259 /* JsxSelfClosingElement */: + case 258 /* JsxElement */: return true; - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 198 /* PrefixUnaryExpression */: - case 199 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -47582,9 +49094,9 @@ var ts; } return false; // Some forms listed here for clarity - case 196 /* VoidExpression */: // Explicit opt-out - case 190 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 208 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 198 /* VoidExpression */: // Explicit opt-out + case 192 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 210 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } @@ -47600,10 +49112,16 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 184 /* ObjectLiteralExpression */ || left.kind === 183 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + } + var leftType; + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); } - var leftType = checkExpression(left, checkMode); var rightType = checkExpression(right, checkMode); switch (operator) { case 39 /* AsteriskToken */: @@ -47725,9 +49243,15 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - checkSpecialAssignment(left, right); - checkAssignmentOperator(rightType); - return getRegularTypeOfObjectLiteral(rightType); + var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; + checkSpecialAssignment(special, right); + if (isJSSpecialPropertyAssignment(special)) { + return leftType; + } + else { + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + } case 26 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); @@ -47736,8 +49260,7 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(left, right) { - var special = ts.getSpecialPropertyAssignmentKind(left.parent); + function checkSpecialAssignment(special, right) { if (special === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { @@ -47794,12 +49317,45 @@ var ts; if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported - checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right); } } } + function isJSSpecialPropertyAssignment(special) { + switch (special) { + case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: + case 5 /* Property */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + var symbol = getSymbolOfNode(left); + var init = ts.getAssignedJavascriptInitializer(right); + return init && ts.isObjectLiteralExpression(init) && + symbol && ts.hasEntries(symbol.exports); + default: + return false; + } + } function reportOperatorError() { - error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); + var leftStr = typeToString(leftType); + var rightStr = typeToString(rightType); + var errNode = errorNode || operatorToken; + if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { + error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr); + } + } + function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { + switch (operatorToken.kind) { + case 34 /* EqualsEqualsEqualsToken */: + case 32 /* EqualsEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); + } + return undefined; } } function isYieldExpressionInClass(node) { @@ -47853,16 +49409,16 @@ var ts; // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. - var returnType = ts.getEffectiveReturnTypeNode(func); + var returnType = getReturnTypeFromAnnotation(func); if (returnType) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; - checkTypeAssignableTo(yieldedType, signatureElementType, node.expression || node, /*headMessage*/ undefined); + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); } // Both yield and yield* expressions have type 'any' return anyType; } function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); + checkTruthinessExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -47875,13 +49431,13 @@ var ts; // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { - error(templateSpan.expression, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1, typeToString(esSymbolType), typeToString(stringType)); + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; } function getContextNode(node) { - if (node.kind === 263 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -47917,7 +49473,7 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 190 /* TypeAssertionExpression */ || node.kind === 208 /* AsExpression */; + return node.kind === 192 /* TypeAssertionExpression */ || node.kind === 210 /* AsExpression */; } function checkDeclarationInitializer(declaration) { var initializer = ts.getEffectiveInitializer(declaration); @@ -48019,7 +49575,7 @@ var ts; function getTypeOfExpression(node, cache) { // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 187 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { + if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -48045,9 +49601,6 @@ var ts; node.contextualType = saveContextualType; return type; } - function checkExpresionNoReturn(node) { - checkExpression(node); - } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -48069,8 +49622,8 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 185 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 186 /* ElementAccessExpression */ && node.parent.expression === node) || + var ok = (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.expression === node) || ((node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || (node.parent.kind === 165 /* TypeQuery */ && node.parent.exprName === node)); if (!ok) { @@ -48106,74 +49659,76 @@ var ts; return trueType; case 86 /* FalseKeyword */: return falseType; - case 202 /* TemplateExpression */: + case 204 /* TemplateExpression */: return checkTemplateExpression(node); case 12 /* RegularExpressionLiteral */: return globalRegExpType; - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 187 /* CallExpression */: + case 189 /* CallExpression */: if (node.expression.kind === 91 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 188 /* NewExpression */: + case 190 /* NewExpression */: return checkCallExpression(node); - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: return checkClassExpression(node); - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 195 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 190 /* TypeAssertionExpression */: - case 208 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: return checkAssertion(node); - case 209 /* NonNullExpression */: + case 211 /* NonNullExpression */: return checkNonNullAssertion(node); - case 210 /* MetaProperty */: + case 212 /* MetaProperty */: return checkMetaProperty(node); - case 194 /* DeleteExpression */: + case 196 /* DeleteExpression */: return checkDeleteExpression(node); - case 196 /* VoidExpression */: + case 198 /* VoidExpression */: return checkVoidExpression(node); - case 197 /* AwaitExpression */: + case 199 /* AwaitExpression */: return checkAwaitExpression(node); - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 204 /* SpreadElement */: + case 206 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 206 /* OmittedExpression */: + case 208 /* OmittedExpression */: return undefinedWideningType; - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: return checkYieldExpression(node); - case 265 /* JsxExpression */: + case 213 /* SyntheticExpression */: + return node.type; + case 268 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 255 /* JsxElement */: + case 258 /* JsxElement */: return checkJsxElement(node, checkMode); - case 256 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 259 /* JsxFragment */: + case 262 /* JsxFragment */: return checkJsxFragment(node, checkMode); - case 263 /* JsxAttributes */: + case 266 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 257 /* JsxOpeningElement */: + case 260 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -48188,7 +49743,7 @@ var ts; checkSourceElement(node.default); var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } if (!hasNonCircularTypeParameterDefault(typeParameter)) { error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); @@ -48202,6 +49757,9 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } + function isRestParameterType(type) { + return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); + } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -48225,24 +49783,16 @@ var ts; if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } + if (func.kind === 195 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - } - return -1; - } function checkTypePredicate(node) { var parent = getTypePredicateParent(node); if (!parent) { @@ -48266,8 +49816,7 @@ var ts; } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), // TODO: GH#18217 - node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -48289,10 +49838,10 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: case 158 /* CallSignature */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: case 163 /* FunctionType */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: @@ -48313,7 +49862,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 181 /* ArrayBindingPattern */ || name.kind === 180 /* ObjectBindingPattern */) { + else if (name.kind === 183 /* ArrayBindingPattern */ || name.kind === 182 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -48326,7 +49875,7 @@ var ts; checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 163 /* FunctionType */ || node.kind === 234 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ || + else if (node.kind === 163 /* FunctionType */ || node.kind === 237 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ || node.kind === 158 /* CallSignature */ || node.kind === 155 /* Constructor */ || node.kind === 159 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); @@ -48388,10 +49937,10 @@ var ts; } } else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node); + checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 160 /* IndexSignature */ && node.kind !== 284 /* JSDocFunctionType */) { + if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -48520,7 +50069,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 236 /* InterfaceDeclaration */) { + if (node.kind === 239 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -48608,7 +50157,7 @@ var ts; // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; - if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); @@ -48630,7 +50179,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 216 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -48781,11 +50330,28 @@ var ts; checkSourceElement(node.elementType); } function checkTupleType(node) { - // Grammar checking - var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); - if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { - grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); + var elementTypes = node.elementTypes; + var seenOptionalElement = false; + for (var i = 0; i < elementTypes.length; i++) { + var e = elementTypes[i]; + if (e.kind === 170 /* RestType */) { + if (i !== elementTypes.length - 1) { + grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); + break; + } + if (!isArrayType(getTypeFromTypeNode(e))) { + error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); + } + } + else if (e.kind === 169 /* OptionalType */) { + seenOptionalElement = true; + } + else if (seenOptionalElement) { + grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } } + checkGrammarForDisallowedTrailingComma(node.elementTypes); ts.forEach(node.elementTypes, checkSourceElement); } function checkUnionOrIntersectionType(node) { @@ -48799,7 +50365,7 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 186 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 188 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -48826,7 +50392,10 @@ var ts; } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, keyofConstraintType, node.typeParameter.constraint); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); } function checkTypeOperator(node) { checkGrammarTypeOperatorNode(node); @@ -48836,10 +50405,11 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 171 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); } function checkImportType(node) { checkSourceElement(node.argument); @@ -48852,9 +50422,9 @@ var ts; var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 236 /* InterfaceDeclaration */ && - n.parent.kind !== 235 /* ClassDeclaration */ && - n.parent.kind !== 205 /* ClassExpression */ && + if (n.parent.kind !== 239 /* InterfaceDeclaration */ && + n.parent.kind !== 238 /* ClassDeclaration */ && + n.parent.kind !== 207 /* ClassExpression */ && n.flags & 4194304 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -48980,11 +50550,11 @@ var ts; } var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var current = declarations_3[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = node.flags & 4194304 /* Ambient */; - var inAmbientContextOrInterface = node.parent.kind === 236 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 239 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -48995,7 +50565,7 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 234 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) { + if (node.kind === 237 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -49124,22 +50694,22 @@ var ts; function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 297 /* JSDocTypedefTag */: - case 292 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: return 2 /* ExportType */; - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 235 /* ClassDeclaration */: - case 238 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 274 /* SourceFile */: + case 277 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values if (!ts.isEntityNameExpression(d.expression)) { return 1 /* ExportValue */; @@ -49147,17 +50717,17 @@ var ts; d = d.expression; /* falls through */ // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 243 /* ImportEqualsDeclaration */: - case 246 /* NamespaceImport */: - case 245 /* ImportClause */: - var result_2 = 0 /* None */; + case 246 /* ImportEqualsDeclaration */: + case 249 /* NamespaceImport */: + case 248 /* ImportClause */: + var result_3 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; - case 232 /* VariableDeclaration */: - case 182 /* BindingElement */: - case 234 /* FunctionDeclaration */: - case 248 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 237 /* FunctionDeclaration */: + case 251 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); @@ -49326,16 +50896,15 @@ var ts; * Checks the return type of an async function to ensure it is a compatible * Promise implementation. * - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. * * @param node The signature to check */ - function checkAsyncFunctionReturnType(node) { + function checkAsyncFunctionReturnType(node, returnTypeNode) { // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -49360,30 +50929,29 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); // TODO: GH#18217 var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (returnType === errorType) { - return errorType; + return; } var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return errorType; + return; } } else { // Always mark the type node as referenced if it points to a value markTypeNodeAsReferenced(returnTypeNode); if (returnType === errorType) { - return errorType; + return; } var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === undefined) { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return errorType; + return; } var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; @@ -49394,28 +50962,27 @@ var ts; else { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); } - return errorType; + return; } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return errorType; + return; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } } - // Get and return the awaited type of the return type. - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } /** Check a decorator */ function checkDecorator(node) { @@ -49428,7 +50995,7 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); @@ -49446,7 +51013,7 @@ var ts; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); // TODO: GH#18217 + var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; @@ -49491,12 +51058,12 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 170 /* IntersectionType */: - case 169 /* UnionType */: + case 172 /* IntersectionType */: + case 171 /* UnionType */: var commonEntityName = void 0; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; - while (typeNode.kind === 173 /* ParenthesizedType */) { + while (typeNode.kind === 175 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 131 /* NeverKeyword */) { @@ -49528,7 +51095,7 @@ var ts; } } return commonEntityName; - case 173 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); case 162 /* TypeReference */: return node.typeName; @@ -49561,7 +51128,7 @@ var ts; checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -49570,9 +51137,13 @@ var ts; } } break; - case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: + var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 154 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); @@ -49612,6 +51183,16 @@ var ts; } checkSourceElement(node.typeExpression); } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); + } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); if (!ts.getParameterSymbolFromJSDoc(node)) { @@ -49647,7 +51228,7 @@ var ts; error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); } var name = getIdentifierFromEntityNameExpression(node.class.expression); - var extend = ts.getClassExtendsHeritageClauseElement(classLike); + var extend = ts.getClassExtendsHeritageElement(classLike); if (extend) { var className = getIdentifierFromEntityNameExpression(extend.expression); if (className && name.escapedText !== className.escapedText) { @@ -49659,7 +51240,7 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node; - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return node.name; default: return undefined; @@ -49703,14 +51284,11 @@ var ts; } var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function - var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ - ? checkAsyncFunctionReturnType(node) // Async function - : getTypeFromTypeNode(returnTypeNode)); // normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } - if (produceDiagnostics && !returnTypeNode) { + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { @@ -49723,6 +51301,13 @@ var ts; getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJavaScriptFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. @@ -49742,27 +51327,27 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; - case 274 /* SourceFile */: - case 239 /* ModuleDeclaration */: - case 213 /* Block */: - case 241 /* CaseBlock */: - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: + case 277 /* SourceFile */: + case 242 /* ModuleDeclaration */: + case 216 /* Block */: + case 244 /* CaseBlock */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; case 155 /* Constructor */: - case 192 /* FunctionExpression */: - case 234 /* FunctionDeclaration */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: @@ -49776,7 +51361,8 @@ var ts; case 159 /* ConstructSignature */: case 163 /* FunctionType */: case 164 /* ConstructorType */: - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 174 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -49787,12 +51373,9 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } - function parameterNameStartsWithUnderscore(parameterName) { - return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); - } - function isIdentifierThatStartsWithUnderScore(node) { + function isIdentifierThatStartsWithUnderscore(node) { return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } function checkUnusedClassMembers(node, addDiagnostic) { @@ -49810,19 +51393,19 @@ var ts; } var symbol = getSymbolOfNode(member); if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; case 155 /* 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 */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } } break; case 160 /* IndexSignature */: - case 212 /* SemicolonClassElement */: + case 215 /* SemicolonClassElement */: // Can't be private break; default: @@ -49834,16 +51417,45 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { + if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + return; + if (node.kind === 174 /* InferType */) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + else { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; - if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol))); + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } function addToGroup(map, key, value, getKey) { var keyString = String(getKey(key)); var group = map.get(keyString); @@ -49872,8 +51484,10 @@ var ts; } for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (ts.isAmbientModule(declaration)) + if (ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { continue; + } if (isImportedDeclaration(declaration)) { addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); } @@ -49885,16 +51499,14 @@ var ts; } } else if (ts.isVariableDeclaration(declaration)) { - if (!isIdentifierThatStartsWithUnderScore(declaration.name) || !ts.isForInOrOfStatement(declaration.parent.parent)) { - addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); - } + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); } else { var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); - if (parameter) { - var name = ts.getNameOfDeclaration(local.valueDeclaration); - if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { @@ -49908,10 +51520,10 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 246 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { - addDiagnostic(0 /* Local */, unuseds.length === 1 + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); } @@ -49926,33 +51538,33 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 232 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 233 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 236 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - addDiagnostic(kind, bindingElements.length === 1 - ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); } } else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; - addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); } } }); unusedVariables.forEach(function (_a) { var declarationList = _a[0], declarations = _a[1]; if (declarationList.declarations.length === declarations.length) { - addDiagnostic(0 /* Local */, declarations.length === 1 + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 214 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var decl = declarations_4[_i]; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); } } }); @@ -49961,22 +51573,22 @@ var ts; switch (name.kind) { case 71 /* Identifier */: return ts.idText(name); - case 181 /* ArrayBindingPattern */: - case 180 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 245 /* ImportClause */ || node.kind === 248 /* ImportSpecifier */ || node.kind === 246 /* NamespaceImport */; + return node.kind === 248 /* ImportClause */ || node.kind === 251 /* ImportSpecifier */ || node.kind === 249 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 245 /* ImportClause */ ? decl : decl.kind === 246 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 248 /* ImportClause */ ? decl : decl.kind === 249 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 213 /* Block */) { + if (node.kind === 216 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -50071,7 +51683,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 274 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -50086,7 +51698,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 274 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -50121,7 +51733,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 232 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 235 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -50133,17 +51745,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 233 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 214 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 217 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 213 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 240 /* ModuleBlock */ || - container.kind === 239 /* ModuleDeclaration */ || - container.kind === 274 /* SourceFile */); + (container.kind === 216 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 243 /* ModuleBlock */ || + container.kind === 242 /* ModuleDeclaration */ || + container.kind === 277 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -50169,7 +51781,7 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 185 /* PropertyAccessExpression */) { + if (n.kind === 187 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } @@ -50189,7 +51801,7 @@ var ts; var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { if (symbol.valueDeclaration.kind === 149 /* Parameter */ || - symbol.valueDeclaration.kind === 182 /* BindingElement */) { + symbol.valueDeclaration.kind === 184 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -50242,8 +51854,8 @@ var ts; checkExpressionCached(node.initializer); } } - if (node.kind === 182 /* BindingElement */) { - if (node.parent.kind === 180 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + if (node.kind === 184 /* BindingElement */) { + if (node.parent.kind === 182 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements @@ -50255,16 +51867,19 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 181 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 183 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); @@ -50277,13 +51892,13 @@ var ts; // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 221 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 224 /* ForInStatement */) { var initializerType = checkExpressionCached(node.initializer); if (strictNullChecks && node.name.elements.length === 0) { checkNonNullType(initializerType, node); } else { - checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); } checkParameterInitializer(node); } @@ -50295,9 +51910,15 @@ var ts; // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); - if (initializer && node.parent.parent.kind !== 221 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(initializer), type, node, /*headMessage*/ undefined); - checkParameterInitializer(node); + if (initializer) { + var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + ts.isObjectLiteralExpression(initializer) && + (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && + ts.hasEntries(symbol.exports); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); + checkParameterInitializer(node); + } } } else { @@ -50310,7 +51931,7 @@ var ts; errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); @@ -50320,7 +51941,7 @@ var ts; if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 232 /* VariableDeclaration */ || node.kind === 182 /* BindingElement */) { + if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -50335,8 +51956,8 @@ var ts; error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 149 /* Parameter */ && right.kind === 232 /* VariableDeclaration */) || - (left.kind === 232 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) { + if ((left.kind === 149 /* Parameter */ && right.kind === 235 /* VariableDeclaration */) || + (left.kind === 235 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -50373,9 +51994,9 @@ var ts; function checkIfStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 215 /* EmptyStatement */) { + if (node.thenStatement.kind === 218 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -50384,23 +52005,30 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); checkSourceElement(node.statement); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); } function checkWhileStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.statement); } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 4096 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 233 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 236 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 233 /* VariableDeclarationList */) { + if (node.initializer.kind === 236 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -50408,7 +52036,7 @@ var ts; } } if (node.condition) - checkExpression(node.condition); + checkTruthinessExpression(node.condition); if (node.incrementor) checkExpression(node.incrementor); checkSourceElement(node.statement); @@ -50434,14 +52062,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 233 /* VariableDeclarationList */) { + if (node.initializer.kind === 236 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 183 /* ArrayLiteralExpression */ || varExpr.kind === 184 /* ObjectLiteralExpression */) { + if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -50455,7 +52083,7 @@ var ts; // because we accessed properties from anyType, or it may have led to an error inside // getElementTypeOfIterable. if (iteratedType) { - checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); } } } @@ -50473,7 +52101,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 233 /* VariableDeclarationList */) { + if (node.initializer.kind === 236 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -50487,7 +52115,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 183 /* ArrayLiteralExpression */ || varExpr.kind === 184 /* ObjectLiteralExpression */) { + if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -50812,10 +52440,6 @@ var ts; checkGrammarBreakOrContinueStatement(node); // TODO: Check that target label is valid } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 156 /* GetAccessor */ - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 157 /* SetAccessor */)) !== undefined; - } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function @@ -50851,11 +52475,11 @@ var ts; } } else if (func.kind === 155 /* Constructor */) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + else if (getReturnTypeFromAnnotation(func)) { if (functionFlags & 2 /* Async */) { // Async function var promisedType = getPromisedTypeOfPromise(returnType); var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -50867,7 +52491,7 @@ var ts; } } else { - checkTypeAssignableTo(exprType, returnType, node); + checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression); } } } @@ -50900,7 +52524,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 267 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 270 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -50912,7 +52536,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 266 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 269 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -50941,7 +52565,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 228 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 231 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -51039,16 +52663,17 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; + var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { + if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; } // perform property check if property or indexer is declared in 'type' // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && - (propDeclaration.kind === 200 /* BinaryExpression */ || - ts.getNameOfDeclaration(propDeclaration).kind === 147 /* ComputedPropertyName */ || + if (propDeclaration && name && + (propDeclaration.kind === 202 /* BinaryExpression */ || + name.kind === 147 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -51135,8 +52760,8 @@ var ts; if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { // Report an error on every conflicting declaration. var name = symbolToString(symbol); - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); } } @@ -51145,8 +52770,8 @@ var ts; function areTypeParametersIdentical(declarations, targetParameters) { var maxTypeArgumentCount = ts.length(targetParameters); var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; // If this declaration has too few or too many type parameters, we report an error var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); var numTypeParameters = sourceParameters.length; @@ -51163,8 +52788,9 @@ var ts; } // If the type parameter node does not have an identical constraint as the resolved // type parameter at this position, we report an error. - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); if (sourceConstraint) { // relax check if later interface augmentation has no constraint if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { @@ -51222,7 +52848,7 @@ var ts; if (!(node.flags & 4194304 /* Ambient */)) { checkClassForStaticPropertyNameConflicts(node); } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); if (baseTypeNode) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); @@ -51234,6 +52860,10 @@ var ts; var staticBaseType = getApparentType(baseConstructorType); checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); + var extendsNode = ts.getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } if (ts.some(baseTypeNode.typeArguments)) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { @@ -51256,8 +52886,9 @@ var ts; // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -51300,7 +52931,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_6 = function (member) { + var _loop_7 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -51319,7 +52950,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_6(member); + _loop_7(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -51345,7 +52976,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 235 /* ClassDeclaration */ || d.kind === 236 /* InterfaceDeclaration */; + return d.kind === 238 /* ClassDeclaration */ || d.kind === 239 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -51384,7 +53015,7 @@ var ts; // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 205 /* ClassExpression */) { + if (derivedClassDecl.kind === 207 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -51498,7 +53129,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 236 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -51561,7 +53192,7 @@ var ts; } // In ambient enum declarations that specify no const modifier, enum member declarations that omit // a value are considered computed members (as opposed to having auto-incremented values). - if (member.parent.flags & 4194304 /* Ambient */ && !ts.isConst(member.parent)) { + if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) { return undefined; } // If the member declaration specifies no value, the member is considered a constant enum member. @@ -51576,7 +53207,7 @@ var ts; } function computeConstantValue(member) { var enumKind = getEnumKind(getSymbolOfNode(member.parent)); - var isConstEnum = ts.isConst(member.parent); + var isConstEnum = ts.isEnumConst(member.parent); var initializer = member.initializer; var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); if (value !== undefined) { @@ -51603,17 +53234,17 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 198 /* PrefixUnaryExpression */: - var value_1 = evaluate(expr.operand); - if (typeof value_1 === "number") { + case 200 /* PrefixUnaryExpression */: + var value_2 = evaluate(expr.operand); + if (typeof value_2 === "number") { switch (expr.operator) { - case 37 /* PlusToken */: return value_1; - case 38 /* MinusToken */: return -value_1; - case 52 /* TildeToken */: return ~value_1; + case 37 /* PlusToken */: return value_2; + case 38 /* MinusToken */: return -value_2; + case 52 /* TildeToken */: return ~value_2; } } break; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -51641,7 +53272,7 @@ var ts; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return evaluate(expr.expression); case 71 /* Identifier */: var identifier = expr; @@ -51649,14 +53280,14 @@ var ts; return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 186 /* ElementAccessExpression */: - case 185 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + case 187 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 185 /* PropertyAccessExpression */) { + if (ex.kind === 187 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -51688,8 +53319,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 71 /* Identifier */ || - node.kind === 185 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 186 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 187 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 188 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && node.argumentExpression.kind === 9 /* StringLiteral */; } function checkEnumDeclaration(node) { @@ -51703,7 +53334,7 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); - var enumIsConst = ts.isConst(node); + var enumIsConst = ts.isEnumConst(node); if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) { error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } @@ -51719,7 +53350,7 @@ var ts; if (enumSymbol.declarations.length > 1) { // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { - if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); @@ -51727,7 +53358,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 238 /* EnumDeclaration */) { + if (declaration.kind !== 241 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -51748,10 +53379,10 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - if ((declaration.kind === 235 /* ClassDeclaration */ || - (declaration.kind === 234 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 238 /* ClassDeclaration */ || + (declaration.kind === 237 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !(declaration.flags & 4194304 /* Ambient */)) { return declaration; } @@ -51814,7 +53445,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 235 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 238 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -51864,23 +53495,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 249 /* ExportAssignment */: - case 250 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + case 253 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 243 /* ImportEqualsDeclaration */: - case 244 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 182 /* BindingElement */: - case 232 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 235 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -51891,12 +53522,12 @@ var ts; break; } // falls through - case 235 /* ClassDeclaration */: - case 238 /* EnumDeclaration */: - case 234 /* FunctionDeclaration */: - case 236 /* InterfaceDeclaration */: - case 239 /* ModuleDeclaration */: - case 237 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 237 /* FunctionDeclaration */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -51924,7 +53555,7 @@ var ts; node = node.left; } while (node.kind !== 71 /* Identifier */); return node; - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 71 /* Identifier */); @@ -51941,9 +53572,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 240 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 274 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 250 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 253 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -51976,14 +53607,14 @@ var ts; (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 252 /* ExportSpecifier */ ? + var message = node.kind === 255 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 252 /* ExportSpecifier */ + && node.kind === 255 /* ExportSpecifier */ && !(target.flags & 67216319 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); @@ -52010,7 +53641,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 246 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -52034,7 +53665,7 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 254 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 67216319 /* Value */) { @@ -52070,18 +53701,18 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 240 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 240 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; - if (node.parent.kind !== 274 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { // export * from "foo" - var moduleSymbol_2 = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol_2 && hasExportAssignmentSymbol(moduleSymbol_2)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol_2)); + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + 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 && moduleKind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768 /* ExportStar */); @@ -52090,7 +53721,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 274 /* SourceFile */ || node.parent.kind === 240 /* ModuleBlock */ || node.parent.kind === 239 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 277 /* SourceFile */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 242 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -52119,8 +53750,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 274 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 239 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -52172,9 +53803,9 @@ var ts; } } // Checks for export * conflicts - var exports = getExportsOfModule(moduleSymbol); - if (exports) { - exports.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -52191,8 +53822,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -52208,7 +53839,7 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 234 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) || + return (declaration.kind !== 237 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { @@ -52226,10 +53857,10 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 239 /* ModuleDeclaration */: - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 234 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 237 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -52267,109 +53898,117 @@ var ts; return checkArrayType(node); case 168 /* TupleType */: return checkTupleType(node); - case 169 /* UnionType */: - case 170 /* IntersectionType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 173 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: + case 169 /* OptionalType */: + case 170 /* RestType */: return checkSourceElement(node.type); - case 175 /* TypeOperator */: + case 176 /* ThisType */: + return checkThisType(node); + case 177 /* TypeOperator */: return checkTypeOperator(node); - case 171 /* ConditionalType */: + case 173 /* ConditionalType */: return checkConditionalType(node); - case 172 /* InferType */: + case 174 /* InferType */: return checkInferType(node); - case 179 /* ImportType */: + case 181 /* ImportType */: return checkImportType(node); - case 290 /* JSDocAugmentsTag */: + case 293 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 297 /* JSDocTypedefTag */: - case 292 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 293 /* JSDocParameterTag */: + case 301 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 300 /* JSDocTypeTag */: + return checkJSDocTypeTag(node); + case 297 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 284 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: checkSignatureDeclaration(node); // falls through - case 282 /* JSDocNonNullableType */: - case 281 /* JSDocNullableType */: - case 279 /* JSDocAllType */: - case 280 /* JSDocUnknownType */: - case 287 /* JSDocTypeLiteral */: + case 285 /* JSDocNonNullableType */: + case 284 /* JSDocNullableType */: + case 282 /* JSDocAllType */: + case 283 /* JSDocUnknownType */: + case 290 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 285 /* JSDocVariadicType */: + case 288 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 278 /* JSDocTypeExpression */: + case 281 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 176 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 177 /* MappedType */: + case 179 /* MappedType */: return checkMappedType(node); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 213 /* Block */: - case 240 /* ModuleBlock */: + case 216 /* Block */: + case 243 /* ModuleBlock */: return checkBlock(node); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return checkVariableStatement(node); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return checkExpressionStatement(node); - case 217 /* IfStatement */: + case 220 /* IfStatement */: return checkIfStatement(node); - case 218 /* DoStatement */: + case 221 /* DoStatement */: return checkDoStatement(node); - case 219 /* WhileStatement */: + case 222 /* WhileStatement */: return checkWhileStatement(node); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return checkForStatement(node); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return checkForInStatement(node); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return checkForOfStatement(node); - case 223 /* ContinueStatement */: - case 224 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: return checkReturnStatement(node); - case 226 /* WithStatement */: + case 229 /* WithStatement */: return checkWithStatement(node); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: return checkSwitchStatement(node); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return checkLabeledStatement(node); - case 229 /* ThrowStatement */: + case 232 /* ThrowStatement */: return checkThrowStatement(node); - case 230 /* TryStatement */: + case 233 /* TryStatement */: return checkTryStatement(node); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 182 /* BindingElement */: + case 184 /* BindingElement */: return checkBindingElement(node); - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return checkClassDeclaration(node); - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return checkImportDeclaration(node); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return checkExportDeclaration(node); - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return checkExportAssignment(node); - case 215 /* EmptyStatement */: - case 231 /* DebuggerStatement */: + case 218 /* EmptyStatement */: + case 234 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 253 /* MissingDeclaration */: + case 256 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -52446,15 +54085,15 @@ var ts; // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { if (deferredNodes) { - deferredNodes.push(node); + var id = "" + getNodeId(node); + deferredNodes.set(id, node); } } function checkDeferredNodes() { - for (var _i = 0, _a = deferredNodes; _i < _a.length; _i++) { - var node = _a[_i]; + deferredNodes.forEach(function (node) { switch (node.kind) { - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); @@ -52463,11 +54102,17 @@ var ts; case 157 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: checkClassExpressionDeferred(node); break; + case 259 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 258 /* JsxElement */: + checkJsxElementDeferred(node); + break; } - } + }); } function checkSourceFile(node) { ts.performance.mark("beforeCheck"); @@ -52492,25 +54137,22 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1 /* TypeChecked */)) { - // If skipLibCheck is enabled, skip type checking if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip type checking if file contains a - // '/// ' directive. - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + if (ts.skipTypeChecking(node, compilerOptions)) { return; } // Grammar checking checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = []; + deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { - if (unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { diagnostics.add(diag); } }); @@ -52589,6 +54231,7 @@ var ts; var symbols = ts.createSymbolTable(); var isStatic = false; populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword return symbolsToArray(symbols); function populateSymbols() { while (location) { @@ -52596,13 +54239,13 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -52610,8 +54253,8 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -52620,7 +54263,7 @@ var ts; copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); } break; - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -52669,10 +54312,10 @@ var ts; function isTypeDeclaration(node) { switch (node.kind) { case 148 /* TypeParameter */: - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 238 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: return true; default: return false; @@ -52686,10 +54329,10 @@ var ts; return node.parent.kind === 162 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 185 /* PropertyAccessExpression */) { + while (node.parent.kind === 187 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 207 /* ExpressionWithTypeArguments */; + return node.parent.kind === 209 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -52720,10 +54363,10 @@ var ts; while (nodeOnRightSide.parent.kind === 146 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 243 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 246 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 249 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 252 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -52749,7 +54392,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 179 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 181 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -52759,7 +54402,7 @@ var ts; return getSymbolOfNode(entityName.parent); } if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 185 /* PropertyAccessExpression */ && + entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -52767,7 +54410,7 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 249 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); @@ -52777,7 +54420,7 @@ var ts; } else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 243 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 246 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } @@ -52795,7 +54438,7 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 207 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { meaning = 67901928 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -52811,10 +54454,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 293 /* JSDocParameterTag */) { + if (entityName.parent.kind === 297 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 296 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -52831,12 +54474,12 @@ var ts; } return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 185 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { + else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 185 /* PropertyAccessExpression */) { + if (entityName.kind === 187 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -52849,7 +54492,7 @@ var ts; var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 262 /* JsxAttribute */) { + else if (entityName.parent.kind === 265 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } if (entityName.parent.kind === 161 /* TypePredicate */) { @@ -52859,7 +54502,7 @@ var ts; return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 274 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -52879,11 +54522,11 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (parent.kind === 182 /* BindingElement */ && - grandParent.kind === 180 /* ObjectBindingPattern */ && + else if (parent.kind === 184 /* BindingElement */ && + grandParent.kind === 182 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; } @@ -52891,7 +54534,7 @@ var ts; } switch (node.kind) { case 71 /* Identifier */: - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: case 146 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 99 /* ThisKeyword */: @@ -52906,7 +54549,7 @@ var ts; return checkExpression(node).symbol; } // falls through - case 174 /* ThisType */: + case 176 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 97 /* SuperKeyword */: return checkExpression(node).symbol; @@ -52924,7 +54567,7 @@ var ts; // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 244 /* ImportDeclaration */ || node.parent.kind === 250 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); @@ -52942,14 +54585,14 @@ var ts; case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: return getSymbolOfNode(node.parent); - case 179 /* ImportType */: + case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 271 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -52967,7 +54610,7 @@ var ts; } if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { var containingClass = ts.getContainingClass(node); var classType = getTypeOfNode(containingClass); typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); @@ -52982,8 +54625,8 @@ var ts; // extends clause of a class. We handle that case here. var classNode = ts.getContainingClass(node); var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -52992,7 +54635,7 @@ var ts; } if (isTypeDeclarationName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } if (ts.isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -53001,10 +54644,10 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); + return symbol ? getTypeOfSymbol(symbol) : errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -53022,28 +54665,28 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 184 /* ObjectLiteralExpression */ || expr.kind === 183 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 186 /* ObjectLiteralExpression */ || expr.kind === 185 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 222 /* ForOfStatement */) { + if (expr.parent.kind === 225 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 200 /* BinaryExpression */) { + if (expr.parent.kind === 202 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 270 /* PropertyAssignment */) { + if (expr.parent.kind === 273 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 183 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 185 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; @@ -53122,7 +54765,7 @@ var ts; if (!ts.isGeneratedIdentifier(nodeIn)) { var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 185 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -53178,7 +54821,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 274 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 277 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -53233,7 +54876,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 213 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -53274,16 +54917,16 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 243 /* ImportEqualsDeclaration */: - case 245 /* ImportClause */: - case 246 /* NamespaceImport */: - case 248 /* ImportSpecifier */: - case 252 /* ExportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return node.expression && node.expression.kind === 71 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) @@ -53293,7 +54936,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 274 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 277 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -53374,22 +55017,23 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 273 /* EnumMember */: - case 185 /* PropertyAccessExpression */: - case 186 /* ElementAccessExpression */: + case 276 /* EnumMember */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 273 /* EnumMember */) { + if (node.kind === 276 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol && (symbol.flags & 8 /* EnumMember */)) { // inline property\index accesses only for const enums - if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { - return getEnumMemberValue(symbol.valueDeclaration); + var member = symbol.valueDeclaration; + if (ts.isEnumConst(member.parent)) { + return getEnumMemberValue(member); } } return undefined; @@ -53527,7 +55171,7 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isConst(node)) { + if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); } @@ -53621,10 +55265,11 @@ var ts; setAccessor: setAccessor, getAccessor: getAccessor }; - } + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } }; function isInHeritageClause(node) { - return node.parent && node.parent.kind === 207 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 268 /* HeritageClause */; + return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -53636,7 +55281,7 @@ var ts; // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries var meaning = 67901928 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 185 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -53687,7 +55332,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 274 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 277 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -53702,12 +55347,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 239 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 242 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 274 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 277 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -53715,10 +55360,14 @@ var ts; var file = _a[_i]; ts.bindSourceFile(file, compilerOptions); } + amalgamatedDuplicates = ts.createMap(); // Initialize global symbol table var augmentations; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { var file = _c[_b]; + if (file.redirectInfo) { + continue; + } if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } @@ -53792,6 +55441,32 @@ var ts; } } } + amalgamatedDuplicates.forEach(function (_a) { + var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; + var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + // If not many things conflict, issue individual errors + if (conflictingKeys.length < 8) { + addErrorsForDuplicates(firstFileInstances, secondFileInstances); + addErrorsForDuplicates(secondFileInstances, firstFileInstances); + return; + } + // Otheriwse issue top-level error since the files appear very identical in terms of what they appear + var list = conflictingKeys.join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + }); + amalgamatedDuplicates = undefined; + function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { + secondFileInstances.forEach(function (locations, symbolName) { + var firstFileEquivalent = firstFileInstances.get(symbolName); + var message = locations.blockScoped + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + locations.instances.forEach(function (node) { + addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); + }); + }); + } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -53885,7 +55560,7 @@ var ts; } switch (modifier.kind) { case 76 /* ConstKeyword */: - if (node.kind !== 238 /* EnumDeclaration */ && node.parent.kind === 235 /* ClassDeclaration */) { + if (node.kind !== 241 /* EnumDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); } break; @@ -53905,7 +55580,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 240 /* ModuleBlock */ || node.parent.kind === 274 /* SourceFile */) { + else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -53928,7 +55603,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 240 /* ModuleBlock */ || node.parent.kind === 274 /* SourceFile */) { + else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } else if (node.kind === 149 /* Parameter */) { @@ -53964,7 +55639,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 235 /* ClassDeclaration */) { + else if (node.parent.kind === 238 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } else if (node.kind === 149 /* Parameter */) { @@ -53973,8 +55648,8 @@ var ts; flags |= 1 /* Export */; break; case 79 /* DefaultKeyword */: - var container = node.parent.kind === 274 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 239 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -53986,13 +55661,13 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 235 /* ClassDeclaration */) { + else if (node.parent.kind === 238 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } else if (node.kind === 149 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 240 /* ModuleBlock */) { + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 243 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; @@ -54002,14 +55677,14 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 235 /* ClassDeclaration */) { + if (node.kind !== 238 /* ClassDeclaration */) { if (node.kind !== 154 /* MethodDeclaration */ && node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 156 /* GetAccessor */ && node.kind !== 157 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 235 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 238 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -54051,7 +55726,7 @@ var ts; } return false; } - else if ((node.kind === 244 /* ImportDeclaration */ || node.kind === 243 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 247 /* ImportDeclaration */ || node.kind === 246 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { @@ -54086,29 +55761,29 @@ var ts; case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 160 /* IndexSignature */: - case 239 /* ModuleDeclaration */: - case 244 /* ImportDeclaration */: - case 243 /* ImportEqualsDeclaration */: - case 250 /* ExportDeclaration */: - case 249 /* ExportAssignment */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 242 /* ModuleDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: case 149 /* Parameter */: return false; default: - if (node.parent.kind === 240 /* ModuleBlock */ || node.parent.kind === 274 /* SourceFile */) { + if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { return false; } switch (node.kind) { - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 236 /* InterfaceDeclaration */: - case 214 /* VariableStatement */: - case 237 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 217 /* VariableStatement */: + case 240 /* TypeAliasDeclaration */: return true; - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); default: ts.Debug.fail(); @@ -54122,9 +55797,9 @@ var ts; function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { case 154 /* MethodDeclaration */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -54255,9 +55930,9 @@ var ts; } function checkGrammarForOmittedArgument(args) { if (args) { - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; - if (arg.kind === 206 /* OmittedExpression */) { + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 208 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -54338,15 +56013,15 @@ var ts; return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 200 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 202 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 234 /* FunctionDeclaration */ || - node.kind === 192 /* FunctionExpression */ || + ts.Debug.assert(node.kind === 237 /* FunctionDeclaration */ || + node.kind === 194 /* FunctionExpression */ || node.kind === 154 /* MethodDeclaration */); if (node.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); @@ -54370,7 +56045,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 272 /* SpreadAssignment */) { + if (prop.kind === 275 /* SpreadAssignment */) { continue; } var name = prop.name; @@ -54378,7 +56053,7 @@ var ts; // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 271 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 274 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -54402,8 +56077,8 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 270 /* PropertyAssignment */: - case 271 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -54453,7 +56128,7 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 264 /* JsxSpreadAttribute */) { + if (attr.kind === 267 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -54463,7 +56138,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 265 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 268 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -54472,12 +56147,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 222 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 225 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 233 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 236 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -54492,20 +56167,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 221 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 221 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 221 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -54574,7 +56249,7 @@ var ts; } var parent = ts.walkUpParenthesizedTypes(node.parent); switch (parent.kind) { - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: var decl = parent; if (decl.name.kind !== 71 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -54612,7 +56287,7 @@ var ts; return true; } if (node.kind === 154 /* MethodDeclaration */) { - if (node.parent.kind === 184 /* ObjectLiteralExpression */) { + if (node.parent.kind === 186 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -54641,7 +56316,7 @@ var ts; return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 236 /* InterfaceDeclaration */) { + else if (node.parent.kind === 239 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } else if (node.parent.kind === 166 /* TypeLiteral */) { @@ -54655,11 +56330,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 223 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 226 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -54667,8 +56342,8 @@ var ts; return false; } break; - case 227 /* SwitchStatement */: - if (node.kind === 224 /* BreakStatement */ && !node.label) { + case 230 /* SwitchStatement */: + if (node.kind === 227 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -54683,13 +56358,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 224 /* BreakStatement */ + var message = node.kind === 227 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 224 /* BreakStatement */ + var message = node.kind === 227 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -54702,9 +56377,6 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - if (node.name.kind === 181 /* ArrayBindingPattern */ || node.name.kind === 180 /* ObjectBindingPattern */) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (node.propertyName) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); } @@ -54716,14 +56388,14 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 198 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 221 /* ForInStatement */ && node.parent.parent.kind !== 222 /* ForOfStatement */) { + if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { if (node.initializer) { - if (ts.isConst(node) && !node.type) { + if (ts.isVarConst(node) && !node.type) { if (!isStringOrNumberLiteralExpression(node.initializer)) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); } @@ -54734,7 +56406,7 @@ var ts; return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } - if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { + if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -54744,19 +56416,19 @@ var ts; if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); } - if (ts.isConst(node)) { + if (ts.isVarConst(node)) { return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); } } } - if (node.exclamationToken && (node.parent.parent.kind !== 214 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 217 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { checkESModuleMarker(node.name); } - var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding @@ -54811,15 +56483,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 217 /* IfStatement */: - case 218 /* DoStatement */: - case 219 /* WhileStatement */: - case 226 /* WithStatement */: - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: + case 220 /* IfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: return false; - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -54829,7 +56501,7 @@ var ts; if (ts.isLet(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); } - else if (ts.isConst(node.declarationList)) { + else if (ts.isVarConst(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); } } @@ -54896,7 +56568,7 @@ var ts; return true; } } - else if (node.parent.kind === 236 /* InterfaceDeclaration */) { + else if (node.parent.kind === 239 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -54933,13 +56605,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 236 /* InterfaceDeclaration */ || - node.kind === 237 /* TypeAliasDeclaration */ || - node.kind === 244 /* ImportDeclaration */ || - node.kind === 243 /* ImportEqualsDeclaration */ || - node.kind === 250 /* ExportDeclaration */ || - node.kind === 249 /* ExportAssignment */ || - node.kind === 242 /* NamespaceExportDeclaration */ || + if (node.kind === 239 /* InterfaceDeclaration */ || + node.kind === 240 /* TypeAliasDeclaration */ || + node.kind === 247 /* ImportDeclaration */ || + node.kind === 246 /* ImportEqualsDeclaration */ || + node.kind === 253 /* ExportDeclaration */ || + node.kind === 252 /* ExportAssignment */ || + node.kind === 245 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -54948,7 +56620,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 214 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 217 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -54975,11 +56647,11 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 213 /* Block */ || node.parent.kind === 240 /* ModuleBlock */ || node.parent.kind === 274 /* SourceFile */) { - var links_1 = getNodeLinks(node.parent); + if (node.parent.kind === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { + var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); } } else { @@ -54997,10 +56669,10 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 178 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 180 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 273 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 276 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -55055,8 +56727,8 @@ var ts; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 248 /* ImportSpecifier */: - case 252 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -55064,14 +56736,14 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 245 /* ImportClause */: // For default import - case 243 /* ImportEqualsDeclaration */: - case 246 /* NamespaceImport */: - case 248 /* ImportSpecifier */: // For rename import `x as y` + case 248 /* ImportClause */: // For default import + case 246 /* ImportEqualsDeclaration */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: // For rename import `x as y` return true; case 71 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 248 /* ImportSpecifier */; + return decl.parent.kind === 251 /* ImportSpecifier */; default: return false; } @@ -55087,8 +56759,12 @@ var ts; JsxNames.Element = "Element"; JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); + function typeIsLiteralType(type) { + return !!(type.flags & 448 /* Literal */); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -55254,7 +56930,7 @@ var ts; } ts.createFileLevelUniqueName = createFileLevelUniqueName; function getGeneratedNameForNode(node, flags) { - var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : ""); + var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : ""); name.autoGenerateFlags = 4 /* Node */ | flags; name.autoGenerateId = nextAutoGenerateId; name.original = node; @@ -55347,10 +57023,9 @@ var ts; } ts.updateQualifiedName = updateQualifiedName; function parenthesizeForComputedName(expression) { - return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) || - expression.kind === 302 /* CommaListExpression */ ? - createParen(expression) : - expression; + return ts.isCommaSequence(expression) + ? createParen(expression) + : expression; } function createComputedPropertyName(expression) { var node = createSynthesizedNode(147 /* ComputedPropertyName */); @@ -55713,14 +57388,38 @@ var ts; return node; } ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { + function updateTupleTypeNode(node, elementTypes) { return node.elementTypes !== elementTypes ? updateNode(createTupleTypeNode(elementTypes), node) : node; } - ts.updateTypleTypeNode = updateTypleTypeNode; + ts.updateTupleTypeNode = updateTupleTypeNode; + function createOptionalTypeNode(type) { + var node = createSynthesizedNode(169 /* OptionalType */); + node.type = ts.parenthesizeArrayTypeMember(type); + return node; + } + ts.createOptionalTypeNode = createOptionalTypeNode; + function updateOptionalTypeNode(node, type) { + return node.type !== type + ? updateNode(createOptionalTypeNode(type), node) + : node; + } + ts.updateOptionalTypeNode = updateOptionalTypeNode; + function createRestTypeNode(type) { + var node = createSynthesizedNode(170 /* RestType */); + node.type = type; + return node; + } + ts.createRestTypeNode = createRestTypeNode; + function updateRestTypeNode(node, type) { + return node.type !== type + ? updateNode(createRestTypeNode(type), node) + : node; + } + ts.updateRestTypeNode = updateRestTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(169 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(171 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -55728,7 +57427,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(170 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(172 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -55747,7 +57446,7 @@ var ts; : node; } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createSynthesizedNode(171 /* ConditionalType */); + var node = createSynthesizedNode(173 /* ConditionalType */); node.checkType = ts.parenthesizeConditionalTypeMember(checkType); node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); node.trueType = trueType; @@ -55765,7 +57464,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(172 /* InferType */); + var node = createSynthesizedNode(174 /* InferType */); node.typeParameter = typeParameter; return node; } @@ -55777,7 +57476,7 @@ var ts; } ts.updateInferTypeNode = updateInferTypeNode; function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { - var node = createSynthesizedNode(179 /* ImportType */); + var node = createSynthesizedNode(181 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = asNodeArray(typeArguments); @@ -55795,7 +57494,7 @@ var ts; } ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(173 /* ParenthesizedType */); + var node = createSynthesizedNode(175 /* ParenthesizedType */); node.type = type; return node; } @@ -55807,11 +57506,11 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(174 /* ThisType */); + return createSynthesizedNode(176 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; function createTypeOperatorNode(operatorOrType, type) { - var node = createSynthesizedNode(175 /* TypeOperator */); + var node = createSynthesizedNode(177 /* TypeOperator */); node.operator = typeof operatorOrType === "number" ? operatorOrType : 128 /* KeyOfKeyword */; node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; @@ -55822,7 +57521,7 @@ var ts; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(176 /* IndexedAccessType */); + var node = createSynthesizedNode(178 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -55836,7 +57535,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(177 /* MappedType */); + var node = createSynthesizedNode(179 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -55854,7 +57553,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(178 /* LiteralType */); + var node = createSynthesizedNode(180 /* LiteralType */); node.literal = literal; return node; } @@ -55867,7 +57566,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(180 /* ObjectBindingPattern */); + var node = createSynthesizedNode(182 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -55879,7 +57578,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(181 /* ArrayBindingPattern */); + var node = createSynthesizedNode(183 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -55891,7 +57590,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(182 /* BindingElement */); + var node = createSynthesizedNode(184 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -55910,7 +57609,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(183 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(185 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -55924,7 +57623,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(184 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(186 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -55938,7 +57637,7 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(185 /* PropertyAccessExpression */); + var node = createSynthesizedNode(187 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); @@ -55955,7 +57654,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(186 /* ElementAccessExpression */); + var node = createSynthesizedNode(188 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -55969,7 +57668,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(187 /* CallExpression */); + var node = createSynthesizedNode(189 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -55985,7 +57684,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(188 /* NewExpression */); + var node = createSynthesizedNode(190 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -56001,7 +57700,7 @@ var ts; } ts.updateNew = updateNew; function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { - var node = createSynthesizedNode(189 /* TaggedTemplateExpression */); + var node = createSynthesizedNode(191 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); if (template) { node.typeArguments = asNodeArray(typeArgumentsOrTemplate); @@ -56024,7 +57723,7 @@ var ts; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(190 /* TypeAssertionExpression */); + var node = createSynthesizedNode(192 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -56038,7 +57737,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(191 /* ParenthesizedExpression */); + var node = createSynthesizedNode(193 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -56050,7 +57749,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(192 /* FunctionExpression */); + var node = createSynthesizedNode(194 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -56074,7 +57773,7 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(193 /* ArrowFunction */); + var node = createSynthesizedNode(195 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); @@ -56084,19 +57783,7 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - 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; - } + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters @@ -56108,7 +57795,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(194 /* DeleteExpression */); + var node = createSynthesizedNode(196 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -56120,7 +57807,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(195 /* TypeOfExpression */); + var node = createSynthesizedNode(197 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -56132,7 +57819,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(196 /* VoidExpression */); + var node = createSynthesizedNode(198 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -56144,7 +57831,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(197 /* AwaitExpression */); + var node = createSynthesizedNode(199 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -56156,7 +57843,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(198 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(200 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -56169,7 +57856,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(199 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(201 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -56182,7 +57869,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(200 /* BinaryExpression */); + var node = createSynthesizedNode(202 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -56199,7 +57886,7 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(201 /* ConditionalExpression */); + var node = createSynthesizedNode(203 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); @@ -56208,17 +57895,7 @@ var ts; return node; } ts.createConditional = createConditional; - 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]; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue @@ -56229,7 +57906,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(202 /* TemplateExpression */); + var node = createSynthesizedNode(204 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -56267,7 +57944,7 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(203 /* YieldExpression */); + var node = createSynthesizedNode(205 /* YieldExpression */); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; @@ -56281,7 +57958,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(204 /* SpreadElement */); + var node = createSynthesizedNode(206 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -56293,7 +57970,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(205 /* ClassExpression */); + var node = createSynthesizedNode(207 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -56314,11 +57991,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(206 /* OmittedExpression */); + return createSynthesizedNode(208 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(207 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(209 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -56332,7 +58009,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(208 /* AsExpression */); + var node = createSynthesizedNode(210 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -56346,7 +58023,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(209 /* NonNullExpression */); + var node = createSynthesizedNode(211 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -56358,7 +58035,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(210 /* MetaProperty */); + var node = createSynthesizedNode(212 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -56372,7 +58049,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(211 /* TemplateSpan */); + var node = createSynthesizedNode(214 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -56386,25 +58063,18 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(212 /* SemicolonClassElement */); + return createSynthesizedNode(215 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(213 /* Block */); + var block = createSynthesizedNode(216 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; return block; } ts.createBlock = createBlock; - /* @internal */ - function createExpressionStatement(expression) { - var node = createSynthesizedNode(216 /* ExpressionStatement */); - node.expression = expression; - return node; - } - ts.createExpressionStatement = createExpressionStatement; function updateBlock(node, statements) { return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) @@ -56412,7 +58082,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(214 /* VariableStatement */); + var node = createSynthesizedNode(217 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -56427,21 +58097,27 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(215 /* EmptyStatement */); + return createSynthesizedNode(218 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; - function createStatement(expression) { - return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression)); + function createExpressionStatement(expression) { + var node = createSynthesizedNode(219 /* ExpressionStatement */); + node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); + return node; } - ts.createStatement = createStatement; - function updateStatement(node, expression) { + ts.createExpressionStatement = createExpressionStatement; + function updateExpressionStatement(node, expression) { return node.expression !== expression - ? updateNode(createStatement(expression), node) + ? updateNode(createExpressionStatement(expression), node) : node; } - ts.updateStatement = updateStatement; + ts.updateExpressionStatement = updateExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + ts.createStatement = createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + ts.updateStatement = updateExpressionStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(217 /* IfStatement */); + var node = createSynthesizedNode(220 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -56457,7 +58133,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(218 /* DoStatement */); + var node = createSynthesizedNode(221 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -56471,7 +58147,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(219 /* WhileStatement */); + var node = createSynthesizedNode(222 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -56485,7 +58161,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(220 /* ForStatement */); + var node = createSynthesizedNode(223 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -56503,7 +58179,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(221 /* ForInStatement */); + var node = createSynthesizedNode(224 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -56519,7 +58195,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(222 /* ForOfStatement */); + var node = createSynthesizedNode(225 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -56537,7 +58213,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(223 /* ContinueStatement */); + var node = createSynthesizedNode(226 /* ContinueStatement */); node.label = asName(label); return node; } @@ -56549,7 +58225,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(224 /* BreakStatement */); + var node = createSynthesizedNode(227 /* BreakStatement */); node.label = asName(label); return node; } @@ -56561,7 +58237,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(225 /* ReturnStatement */); + var node = createSynthesizedNode(228 /* ReturnStatement */); node.expression = expression; return node; } @@ -56573,7 +58249,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(226 /* WithStatement */); + var node = createSynthesizedNode(229 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -56587,7 +58263,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(227 /* SwitchStatement */); + var node = createSynthesizedNode(230 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -56601,7 +58277,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(228 /* LabeledStatement */); + var node = createSynthesizedNode(231 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -56615,7 +58291,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(229 /* ThrowStatement */); + var node = createSynthesizedNode(232 /* ThrowStatement */); node.expression = expression; return node; } @@ -56627,7 +58303,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(230 /* TryStatement */); + var node = createSynthesizedNode(233 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -56643,11 +58319,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(231 /* DebuggerStatement */); + return createSynthesizedNode(234 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(232 /* VariableDeclaration */); + var node = createSynthesizedNode(235 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -56664,7 +58340,7 @@ var ts; ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(233 /* VariableDeclarationList */); + var node = createSynthesizedNode(236 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -56677,7 +58353,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(234 /* FunctionDeclaration */); + var node = createSynthesizedNode(237 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -56703,7 +58379,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(235 /* ClassDeclaration */); + var node = createSynthesizedNode(238 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -56725,7 +58401,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(236 /* InterfaceDeclaration */); + var node = createSynthesizedNode(239 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -56747,7 +58423,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(237 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(240 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -56767,7 +58443,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(238 /* EnumDeclaration */); + var node = createSynthesizedNode(241 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -56786,7 +58462,7 @@ var ts; ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createSynthesizedNode(239 /* ModuleDeclaration */); + var node = createSynthesizedNode(242 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -56805,7 +58481,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(240 /* ModuleBlock */); + var node = createSynthesizedNode(243 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -56817,7 +58493,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(241 /* CaseBlock */); + var node = createSynthesizedNode(244 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -56829,7 +58505,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(242 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(245 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -56841,7 +58517,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(243 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(246 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -56859,7 +58535,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(244 /* ImportDeclaration */); + var node = createSynthesizedNode(247 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -56877,7 +58553,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(245 /* ImportClause */); + var node = createSynthesizedNode(248 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -56891,7 +58567,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(246 /* NamespaceImport */); + var node = createSynthesizedNode(249 /* NamespaceImport */); node.name = name; return node; } @@ -56903,7 +58579,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(247 /* NamedImports */); + var node = createSynthesizedNode(250 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -56915,7 +58591,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(248 /* ImportSpecifier */); + var node = createSynthesizedNode(251 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -56929,7 +58605,7 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(249 /* ExportAssignment */); + var node = createSynthesizedNode(252 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; @@ -56946,7 +58622,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(250 /* ExportDeclaration */); + var node = createSynthesizedNode(253 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -56964,7 +58640,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(251 /* NamedExports */); + var node = createSynthesizedNode(254 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -56976,7 +58652,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(252 /* ExportSpecifier */); + var node = createSynthesizedNode(255 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -56991,7 +58667,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(254 /* ExternalModuleReference */); + var node = createSynthesizedNode(257 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -57004,7 +58680,7 @@ var ts; ts.updateExternalModuleReference = updateExternalModuleReference; // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(255 /* JsxElement */); + var node = createSynthesizedNode(258 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -57020,9 +58696,9 @@ var ts; } ts.updateJsxElement = updateJsxElement; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(256 /* JsxSelfClosingElement */); + var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -57036,9 +58712,9 @@ var ts; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createSynthesizedNode(257 /* JsxOpeningElement */); + var node = createSynthesizedNode(260 /* JsxOpeningElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -57052,7 +58728,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(258 /* JsxClosingElement */); + var node = createSynthesizedNode(261 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -57064,7 +58740,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxFragment(openingFragment, children, closingFragment) { - var node = createSynthesizedNode(259 /* JsxFragment */); + var node = createSynthesizedNode(262 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -57080,7 +58756,7 @@ var ts; } ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(262 /* JsxAttribute */); + var node = createSynthesizedNode(265 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -57094,7 +58770,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(263 /* JsxAttributes */); + var node = createSynthesizedNode(266 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -57106,7 +58782,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(264 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(267 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -57118,7 +58794,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(265 /* JsxExpression */); + var node = createSynthesizedNode(268 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -57132,7 +58808,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(266 /* CaseClause */); + var node = createSynthesizedNode(269 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -57146,7 +58822,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(267 /* DefaultClause */); + var node = createSynthesizedNode(270 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -57158,7 +58834,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(268 /* HeritageClause */); + var node = createSynthesizedNode(271 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -57171,7 +58847,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(269 /* CatchClause */); + var node = createSynthesizedNode(272 /* CatchClause */); node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -57186,7 +58862,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(270 /* PropertyAssignment */); + var node = createSynthesizedNode(273 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = ts.parenthesizeExpressionForList(initializer); @@ -57201,7 +58877,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(271 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(274 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -57215,7 +58891,7 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(272 /* SpreadAssignment */); + var node = createSynthesizedNode(275 /* SpreadAssignment */); node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } @@ -57228,7 +58904,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(273 /* EnumMember */); + var node = createSynthesizedNode(276 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -57249,7 +58925,7 @@ var ts; (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { - var updated = createSynthesizedNode(274 /* SourceFile */); + var updated = createSynthesizedNode(277 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -57333,7 +59009,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(300 /* NotEmittedStatement */); + var node = createSynthesizedNode(305 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -57345,7 +59021,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(304 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -57357,7 +59033,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(303 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -57372,7 +59048,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(301 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -57388,7 +59064,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 302 /* CommaListExpression */) { + if (node.kind === 307 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -57398,7 +59074,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(302 /* CommaListExpression */); + var node = createSynthesizedNode(307 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -57411,24 +59087,27 @@ var ts; ts.updateCommaList = updateCommaList; function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = ts.createNode(275 /* Bundle */); + var node = ts.createNode(278 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; - function createUnparsedSourceFile(text, map) { - var node = ts.createNode(276 /* UnparsedSource */); + function createUnparsedSourceFile(text, mapPath, map) { + var node = ts.createNode(279 /* UnparsedSource */); node.text = text; + node.sourceMapPath = mapPath; node.sourceMapText = map; return node; } ts.createUnparsedSourceFile = createUnparsedSourceFile; - function createInputFiles(javascript, declaration, javascriptMapText, declarationMapText) { - var node = ts.createNode(277 /* InputFiles */); + function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { + var node = ts.createNode(280 /* InputFiles */); node.javascriptText = javascript; + node.javascriptMapPath = javascriptMapPath; node.javascriptMapText = javascriptMapText; node.declarationText = declaration; + node.declarationMapPath = declarationMapPath; node.declarationMapText = declarationMapText; return node; } @@ -57566,7 +59245,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 274 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -58077,7 +59756,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 228 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -58095,13 +59774,13 @@ var ts; case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return false; - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -58128,7 +59807,7 @@ var ts; } else { switch (callee.kind) { - case 185 /* PropertyAccessExpression */: { + case 187 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -58141,7 +59820,7 @@ var ts; } break; } - case 186 /* ElementAccessExpression */: { + case 188 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -58201,9 +59880,9 @@ var ts; case 156 /* GetAccessor */: case 157 /* SetAccessor */: return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); case 154 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); @@ -58528,7 +60207,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 191 /* ParenthesizedExpression */) { + if (skipped.kind === 193 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -58562,9 +60241,14 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(200 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(200 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1 /* LessThan */: @@ -58572,7 +60256,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 203 /* YieldExpression */) { + && operand.kind === 205 /* YieldExpression */) { return false; } return true; @@ -58660,7 +60344,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 200 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -58675,7 +60359,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(201 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(203 /* ConditionalExpression */, 55 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -58689,8 +60373,7 @@ var ts; // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence var emittedExpression = ts.skipPartiallyEmittedExpressions(e); - return emittedExpression.kind === 200 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || - emittedExpression.kind === 302 /* CommaListExpression */ + return isCommaSequence(emittedExpression) ? ts.createParen(e) : e; } @@ -58708,12 +60391,15 @@ var ts; */ function parenthesizeDefaultExpression(e) { var check = ts.skipPartiallyEmittedExpressions(e); - return (check.kind === 205 /* ClassExpression */ || - check.kind === 192 /* FunctionExpression */ || - check.kind === 302 /* CommaListExpression */ || - ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */) - ? ts.createParen(e) - : e; + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; } ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; /** @@ -58725,9 +60411,9 @@ var ts; function parenthesizeForNew(expression) { var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 187 /* CallExpression */: + case 189 /* CallExpression */: return ts.createParen(expression); - case 188 /* NewExpression */: + case 190 /* NewExpression */: return !leftmostExpr.arguments ? ts.createParen(expression) : expression; @@ -58750,7 +60436,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 188 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 190 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -58788,7 +60474,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(200 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, 26 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -58799,27 +60485,27 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 192 /* FunctionExpression */ || kind === 193 /* ArrowFunction */) { + if (kind === 194 /* FunctionExpression */ || kind === 195 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 184 /* ObjectLiteralExpression */ || leftmostExpressionKind === 192 /* FunctionExpression */) { + if (leftmostExpressionKind === 186 /* ObjectLiteralExpression */ || leftmostExpressionKind === 194 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeConditionalTypeMember(member) { - return member.kind === 171 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + return member.kind === 173 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; } ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 169 /* UnionType */: - case 170 /* IntersectionType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: case 163 /* FunctionType */: case 164 /* ConstructorType */: return ts.createParenthesizedType(member); @@ -58830,8 +60516,8 @@ var ts; function parenthesizeArrayTypeMember(member) { switch (member.kind) { case 165 /* TypeQuery */: - case 175 /* TypeOperator */: - case 172 /* InferType */: + case 177 /* TypeOperator */: + case 174 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -58857,25 +60543,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: node = node.operand; continue; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: node = node.left; continue; - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: node = node.condition; continue; - case 187 /* CallExpression */: + case 191 /* TaggedTemplateExpression */: + node = node.tag; + continue; + case 189 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 186 /* ElementAccessExpression */: - case 185 /* PropertyAccessExpression */: - node = node.expression; - continue; - case 301 /* PartiallyEmittedExpression */: + case 210 /* AsExpression */: + case 188 /* ElementAccessExpression */: + case 187 /* PropertyAccessExpression */: + case 211 /* NonNullExpression */: + case 306 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -58883,12 +60572,17 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 184 /* ObjectLiteralExpression */) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 186 /* ObjectLiteralExpression */)) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; + function isCommaSequence(node) { + return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || + node.kind === 307 /* CommaListExpression */; + } + ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; (function (OuterExpressionKinds) { OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; @@ -58899,13 +60593,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 190 /* TypeAssertionExpression */: - case 208 /* AsExpression */: - case 209 /* NonNullExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: + case 211 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 301 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -58930,7 +60624,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 209 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 211 /* NonNullExpression */) { node = node.expression; } return node; @@ -58938,11 +60632,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 191 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 190 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 208 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 209 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 301 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 193 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -58960,7 +60654,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 191 /* ParenthesizedExpression */ + return node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -59025,10 +60719,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 244 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 247 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 250 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 253 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -59147,7 +60841,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -59159,11 +60853,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 272 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -59196,11 +60890,11 @@ var ts; function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { case 149 /* Parameter */: - case 182 /* BindingElement */: + case 184 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 204 /* SpreadElement */: - case 272 /* SpreadAssignment */: + case 206 /* SpreadElement */: + case 275 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -59212,55 +60906,60 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 182 /* BindingElement */: + case 184 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` // `1` in `let { 1: b } = ...` if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } break; - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` // `1` in `({ 1: b } = ...)` if (bindingElement.name) { var propertyName = bindingElement.name; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } break; - case 272 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) ? target.expression : target; } ts.Debug.fail("Invalid property name for binding element."); } ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } /** * Gets the elements of a BindingOrAssignmentPattern */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 180 /* ObjectBindingPattern */: - case 181 /* ArrayBindingPattern */: - case 183 /* ArrayLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + case 185 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -59300,11 +60999,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 181 /* ArrayBindingPattern */: - case 183 /* ArrayLiteralExpression */: + case 183 /* ArrayBindingPattern */: + case 185 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 180 /* ObjectBindingPattern */: - case 184 /* ObjectLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 186 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -59428,7 +61127,7 @@ var ts; context.startLexicalEnvironment(); statements = visitNodes(statements, visitor, ts.isStatement, start); if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { - statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements); + statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements); } var declarations = context.endLexicalEnvironment(); return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); @@ -59465,7 +61164,7 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 174 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 176 /* ThisType */) { return node; } switch (kind) { @@ -59520,217 +61219,221 @@ var ts; case 167 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); case 168 /* TupleType */: - return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 169 /* UnionType */: + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + case 169 /* OptionalType */: + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 170 /* RestType */: + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 171 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 170 /* IntersectionType */: + case 172 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 171 /* ConditionalType */: + case 173 /* ConditionalType */: return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); - case 172 /* InferType */: + case 174 /* InferType */: return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 179 /* ImportType */: + case 181 /* ImportType */: return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 173 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 175 /* TypeOperator */: + case 177 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 176 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 177 /* MappedType */: + case 179 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 178 /* LiteralType */: + case 180 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 180 /* ObjectBindingPattern */: + case 182 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 181 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 182 /* BindingElement */: + case 184 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 187 /* CallExpression */: + case 189 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 188 /* NewExpression */: + case 190 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 190 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 192 /* FunctionExpression */: + case 194 /* 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 193 /* ArrowFunction */: + case 195 /* 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), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 194 /* DeleteExpression */: + case 196 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 195 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 196 /* VoidExpression */: + case 198 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 197 /* AwaitExpression */: + case 199 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: 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 202 /* TemplateExpression */: + case 204 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 204 /* SpreadElement */: + case 206 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 208 /* AsExpression */: + case 210 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 209 /* NonNullExpression */: + case 211 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 210 /* MetaProperty */: + case 212 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 211 /* TemplateSpan */: + case 214 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 213 /* Block */: + case 216 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 216 /* ExpressionStatement */: - return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 217 /* IfStatement */: + case 219 /* ExpressionStatement */: + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 220 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 218 /* DoStatement */: + case 221 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 219 /* WhileStatement */: + case 222 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 223 /* ContinueStatement */: + case 226 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 224 /* BreakStatement */: + case 227 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 226 /* WithStatement */: + case 229 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 229 /* ThrowStatement */: + case 232 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 230 /* TryStatement */: + case 233 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 233 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), 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 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 242 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 245 /* ImportClause */: + case 248 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 246 /* NamespaceImport */: + case 249 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 247 /* NamedImports */: + case 250 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 248 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 251 /* NamedExports */: + case 254 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 252 /* ExportSpecifier */: + case 255 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 254 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 255 /* JsxElement */: + case 258 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 256 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 257 /* JsxOpeningElement */: + case 260 /* JsxOpeningElement */: return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 258 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 259 /* JsxFragment */: + case 262 /* JsxFragment */: return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 262 /* JsxAttribute */: + case 265 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 263 /* JsxAttributes */: + case 266 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 264 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 265 /* JsxExpression */: + case 268 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 266 /* CaseClause */: + case 269 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 267 /* DefaultClause */: + case 270 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 268 /* HeritageClause */: + case 271 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 272 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 273 /* EnumMember */: + case 276 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 274 /* SourceFile */: + case 277 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 301 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 302 /* CommaListExpression */: + case 307 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -59776,17 +61479,17 @@ var ts; return initial; } // We do not yet support types. - if ((kind >= 161 /* TypePredicate */ && kind <= 178 /* LiteralType */)) { + if ((kind >= 161 /* TypePredicate */ && kind <= 180 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 212 /* SemicolonClassElement */: - case 215 /* EmptyStatement */: - case 206 /* OmittedExpression */: - case 231 /* DebuggerStatement */: - case 300 /* NotEmittedStatement */: + case 215 /* SemicolonClassElement */: + case 218 /* EmptyStatement */: + case 208 /* OmittedExpression */: + case 234 /* DebuggerStatement */: + case 305 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -59853,49 +61556,49 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 180 /* ObjectBindingPattern */: - case 181 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 182 /* BindingElement */: + case 184 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 187 /* CallExpression */: + case 189 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 188 /* NewExpression */: + case 190 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); result = reduceNode(node.template, cbNode, result); break; - case 190 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -59903,123 +61606,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 191 /* ParenthesizedExpression */: - case 194 /* DeleteExpression */: - case 195 /* TypeOfExpression */: - case 196 /* VoidExpression */: - case 197 /* AwaitExpression */: - case 203 /* YieldExpression */: - case 204 /* SpreadElement */: - case 209 /* NonNullExpression */: + case 193 /* ParenthesizedExpression */: + case 196 /* DeleteExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 199 /* AwaitExpression */: + case 205 /* YieldExpression */: + case 206 /* SpreadElement */: + case 211 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 198 /* PrefixUnaryExpression */: - case 199 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 202 /* TemplateExpression */: + case 204 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 208 /* AsExpression */: + case 210 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 211 /* TemplateSpan */: + case 214 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 213 /* Block */: + case 216 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 217 /* IfStatement */: + case 220 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 218 /* DoStatement */: + case 221 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 219 /* WhileStatement */: - case 226 /* WithStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 220 /* ForStatement */: + case 223 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 225 /* ReturnStatement */: - case 229 /* ThrowStatement */: + case 228 /* ReturnStatement */: + case 232 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 230 /* TryStatement */: + case 233 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 233 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -60028,7 +61731,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -60036,139 +61739,139 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 245 /* ImportClause */: + case 248 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 246 /* NamespaceImport */: + case 249 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 247 /* NamedImports */: - case 251 /* NamedExports */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 248 /* ImportSpecifier */: - case 252 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 254 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 255 /* JsxElement */: + case 258 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 259 /* JsxFragment */: + case 262 /* JsxFragment */: result = reduceNode(node.openingFragment, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingFragment, cbNode, result); break; - case 256 /* JsxSelfClosingElement */: - case 257 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 263 /* JsxAttributes */: + case 266 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 258 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 262 /* JsxAttribute */: + case 265 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 264 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 265 /* JsxExpression */: + case 268 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 266 /* CaseClause */: + case 269 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 267 /* DefaultClause */: + case 270 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 268 /* HeritageClause */: + case 271 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 269 /* CatchClause */: + case 272 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 272 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 273 /* EnumMember */: + case 276 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 274 /* SourceFile */: + case 277 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 301 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 302 /* CommaListExpression */: + case 307 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -60182,8 +61885,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) - : ts.prependStatements(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -60227,8 +61930,8 @@ var ts; } var subtreeFlags = 0 /* None */; var nodeArrayFlags = 0 /* None */; - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; subtreeFlags |= aggregateTransformFlagsForNode(node); nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; } @@ -60241,7 +61944,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 207 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 209 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -60327,6 +62030,292 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } + ts.createSourceFileLikeCache = createSourceFileLikeCache; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + var sourcemaps; + (function (sourcemaps) { + sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; + function decode(host, mapPath, map, program, fallbackCache) { + if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } + var currentDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; + var decodedMappings; + var generatedOrderedMappings; + var sourceOrderedMappings; + return { + getOriginalPosition: getOriginalPosition, + getGeneratedPosition: getGeneratedPosition + }; + function getGeneratedPosition(loc) { + var maps = getSourceOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { + return loc; + } + return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos + } + function getOriginalPosition(loc) { + var maps = getGeneratedOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos + } + function getSourceFileLike(fileName, location) { + // Lookup file in program, if provided + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + var file = program && program.getSourceFile(path); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (!file || file.resolvedPath !== path) { + // Otherwise check the cache (which may hit disk) + return fallbackCache.get(path); + } + return file; + } + function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { + var file = getSourceFileLike(fileName, directory); + if (!file) { + return -1; + } + return ts.getPositionOfLineAndCharacter(file, line, character); + } + function getDecodedMappings() { + return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); + } + function getSourceOrderedMappings() { + return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); + } + function getGeneratedOrderedMappings() { + return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); + } + function compareProcessedPositionSourcePositions(a, b) { + return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || + ts.compareValues(a.sourcePosition, b.sourcePosition); + } + function compareProcessedPositionEmittedPositions(a, b) { + return ts.compareValues(a.emittedPosition, b.emittedPosition); + } + function processPosition(position) { + var sourcePath = map.sources[position.sourceIndex]; + return { + emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), + sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), + sourcePath: sourcePath, + }; + } + } + sourcemaps.decode = decode; + /*@internal*/ + function decodeMappings(map) { + var state = { + encodedText: map.mappings, + currentNameIndex: undefined, + sourceMapNamesLength: map.names ? map.names.length : undefined, + currentEmittedColumn: 0, + currentEmittedLine: 0, + currentSourceColumn: 0, + currentSourceLine: 0, + currentSourceIndex: 0, + decodingIndex: 0 + }; + function captureSpan() { + return { + emittedColumn: state.currentEmittedColumn, + emittedLine: state.currentEmittedLine, + sourceColumn: state.currentSourceColumn, + sourceIndex: state.currentSourceIndex, + sourceLine: state.currentSourceLine, + nameIndex: state.currentNameIndex + }; + } + return { + get decodingIndex() { return state.decodingIndex; }, + get error() { return state.error; }, + get lastSpan() { return captureSpan(); }, + next: function () { + if (hasCompletedDecoding(state) || state.error) + return { done: true, value: undefined }; + if (!decodeSinglePosition(state)) + return { done: true, value: undefined }; + return { done: false, value: captureSpan() }; + } + }; + } + sourcemaps.decodeMappings = decodeMappings; + function calculateDecodedMappings(map, processPosition, host) { + var decoder = decodeMappings(map); + var positions = ts.arrayFrom(decoder, processPosition); + if (decoder.error) { + if (host && host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); + } + return []; + } + return positions; + } + function hasCompletedDecoding(state) { + return state.decodingIndex === state.encodedText.length; + } + function decodeSinglePosition(state) { + while (state.decodingIndex < state.encodedText.length) { + var char = state.encodedText.charCodeAt(state.decodingIndex); + if (char === 59 /* semicolon */) { + // New line + state.currentEmittedLine++; + state.currentEmittedColumn = 0; + state.decodingIndex++; + continue; + } + if (char === 44 /* comma */) { + // Next entry is on same line - no action needed + state.decodingIndex++; + continue; + } + // Read the current position + // 1. Column offset from prev read jsColumn + state.currentEmittedColumn += base64VLQFormatDecode(); + // Incorrect emittedColumn dont support this map + if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { + return false; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { + return false; + } + // 2. Relative sourceIndex + state.currentSourceIndex += base64VLQFormatDecode(); + // Incorrect sourceIndex dont support this map + if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { + return false; + } + // Dont support reading mappings that dont have information about original source position + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { + return false; + } + // 3. Relative sourceLine 0 based + state.currentSourceLine += base64VLQFormatDecode(); + // Incorrect sourceLine dont support this map + if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { + return false; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { + return false; + } + // 4. Relative sourceColumn 0 based + state.currentSourceColumn += base64VLQFormatDecode(); + // Incorrect sourceColumn dont support this map + if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { + return false; + } + // 5. Check if there is name: + if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { + if (state.currentNameIndex === undefined) { + state.currentNameIndex = 0; + } + state.currentNameIndex += base64VLQFormatDecode(); + // Incorrect nameIndex dont support this map + // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap + // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { + // return; + // } + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { + return false; + } + // Entry should be complete + return true; + } + createErrorIfCondition(/*condition*/ true, "No encoded entry found"); + return false; + function createErrorIfCondition(condition, errormsg) { + if (state.error) { + // An error was already reported + return true; + } + if (condition) { + state.error = errormsg; + } + return condition; + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; state.decodingIndex++) { + if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { + return undefined; // TODO: GH#18217 + } + // 6 digit number + var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + function base64FormatDecode(char) { + return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + } + function isSourceMappingSegmentEnd(encodedText, pos) { + return (pos === encodedText.length || + encodedText.charCodeAt(pos) === 44 /* comma */ || + encodedText.charCodeAt(pos) === 59 /* semicolon */); + } + })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { function getOriginalNodeId(node) { node = ts.getOriginalNode(node); @@ -60346,7 +62335,7 @@ var ts; function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 274 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 277 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -60392,7 +62381,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -60400,13 +62389,13 @@ var ts; externalImports.push(node); hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; - case 243 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 254 /* ExternalModuleReference */) { + case 246 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -60436,13 +62425,13 @@ var ts; } } break; - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -60450,7 +62439,7 @@ var ts; } } break; - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -60470,7 +62459,7 @@ var ts; } } break; - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -60950,7 +62939,7 @@ var ts; var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); return ts.createElementAccess(value, argumentExpression); } - else if (ts.isStringOrNumericLiteral(propertyName)) { + else if (ts.isStringOrNumericLiteralLike(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); @@ -61086,13 +63075,14 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(185 /* PropertyAccessExpression */); - context.enableSubstitution(186 /* ElementAccessExpression */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(188 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; - var currentScope; + var currentLexicalScope; + var currentNameScope; var currentScopeFirstDeclarationsOfName; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. @@ -61116,15 +63106,15 @@ var ts; var pendingExpressions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 275 /* Bundle */) { + if (node.kind === 278 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 277 /* InputFiles */) { - return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapText); + if (prepend.kind === 280 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); } return prepend; })); @@ -61151,16 +63141,18 @@ var ts; */ function saveStateAndInvoke(node, f) { // Save state - var savedCurrentScope = currentScope; + var savedCurrentScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); // Restore state - if (currentScope !== savedCurrentScope) { + if (currentLexicalScope !== savedCurrentScope) { currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } - currentScope = savedCurrentScope; + currentLexicalScope = savedCurrentScope; + currentNameScope = savedCurrentNameScope; return visited; } /** @@ -61170,15 +63162,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 274 /* SourceFile */: - case 241 /* CaseBlock */: - case 240 /* ModuleBlock */: - case 213 /* Block */: - currentScope = node; + case 277 /* SourceFile */: + case 244 /* CaseBlock */: + case 243 /* ModuleBlock */: + case 216 /* Block */: + currentLexicalScope = node; + currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 235 /* ClassDeclaration */: - case 234 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -61190,7 +63183,11 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 235 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 238 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } + if (ts.isClassDeclaration(node)) { + // XXX: should probably also cover interfaces and type aliases that can have type variables? + currentNameScope = node; } break; } @@ -61234,10 +63231,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: - case 243 /* ImportEqualsDeclaration */: - case 249 /* ExportAssignment */: - case 250 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 252 /* ExportAssignment */: + case 253 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -61258,13 +63255,13 @@ var ts; return node; } switch (node.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitImportDeclaration(node); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -61284,11 +63281,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 250 /* ExportDeclaration */ || - node.kind === 244 /* ImportDeclaration */ || - node.kind === 245 /* ImportClause */ || - (node.kind === 243 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 254 /* ExternalModuleReference */)) { + if (node.kind === 253 /* ExportDeclaration */ || + node.kind === 247 /* ImportDeclaration */ || + node.kind === 248 /* ImportClause */ || + (node.kind === 246 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 257 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -61330,7 +63327,7 @@ var ts; case 154 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 212 /* SemicolonClassElement */: + case 215 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); @@ -61371,6 +63368,8 @@ var ts; // TypeScript accessibility and readonly modifiers are elided. case 167 /* ArrayType */: case 168 /* TupleType */: + case 169 /* OptionalType */: + case 170 /* RestType */: case 166 /* TypeLiteral */: case 161 /* TypePredicate */: case 148 /* TypeParameter */: @@ -61386,36 +63385,36 @@ var ts; case 163 /* FunctionType */: case 165 /* TypeQuery */: case 162 /* TypeReference */: - case 169 /* UnionType */: - case 170 /* IntersectionType */: - case 171 /* ConditionalType */: - case 173 /* ParenthesizedType */: - case 174 /* ThisType */: - case 175 /* TypeOperator */: - case 176 /* IndexedAccessType */: - case 177 /* MappedType */: - case 178 /* LiteralType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 173 /* ConditionalType */: + case 175 /* ParenthesizedType */: + case 176 /* ThisType */: + case 177 /* TypeOperator */: + case 178 /* IndexedAccessType */: + case 179 /* MappedType */: + case 180 /* LiteralType */: // TypeScript type nodes are elided. case 160 /* IndexSignature */: // TypeScript index signatures are elided. case 150 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; case 152 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 242 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; case 155 /* Constructor */: return visitConstructor(node); - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -61426,7 +63425,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -61437,13 +63436,13 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 268 /* HeritageClause */: + case 271 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); case 154 /* MethodDeclaration */: @@ -61456,13 +63455,13 @@ var ts; case 157 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); case 149 /* Parameter */: @@ -61475,35 +63474,35 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 190 /* TypeAssertionExpression */: - case 208 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 187 /* CallExpression */: + case 189 /* CallExpression */: return visitCallExpression(node); - case 188 /* NewExpression */: + case 190 /* NewExpression */: return visitNewExpression(node); - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 209 /* NonNullExpression */: + case 211 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: @@ -61539,7 +63538,7 @@ var ts; var facts = 0 /* None */; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; - var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) @@ -61582,7 +63581,7 @@ var ts; var statements = [classStatement]; // Write any pending expressions from elided or moved computed property names if (ts.some(pendingExpressions)) { - statements.push(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); } pendingExpressions = savedPendingExpressions; // Emit static property assignment. Because classDeclaration is lexically evaluated, @@ -61620,7 +63619,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, context.endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -61943,7 +63942,7 @@ var ts; // // super(...arguments); // - statements.push(ts.createStatement(ts.createCall(ts.createSuper(), + statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } // Add the property initializers. Transforms this: @@ -61985,7 +63984,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 216 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -62022,7 +64021,7 @@ var ts; ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); var localName = ts.getMutableClone(name); ts.setEmitFlags(localName, 1536 /* NoComments */); - return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); } /** * Gets all property declarations with initializers on either the static or instance side of a class. @@ -62069,9 +64068,10 @@ var ts; function addInitializedPropertyStatements(statements, properties, receiver) { for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { var property = properties_10[_i]; - var statement = ts.createStatement(transformInitializedProperty(property, receiver)); + var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); statements.push(statement); } } @@ -62089,6 +64089,7 @@ var ts; ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); expressions.push(expression); } return expressions; @@ -62293,8 +64294,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { - var member = members_4[_i]; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -62372,7 +64373,7 @@ var ts; function addConstructorDecorationStatement(statements, node) { var expression = generateConstructorDecorationExpression(node); if (expression) { - statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); + statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node)); } } /** @@ -62499,8 +64500,8 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: @@ -62509,6 +64510,11 @@ var ts; } return false; } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } /** * Serializes the type of a node for use with decorator type metadata. * @@ -62518,12 +64524,12 @@ var ts; switch (node.kind) { case 152 /* PropertyDeclaration */: case 149 /* Parameter */: - case 156 /* GetAccessor */: return serializeTypeNode(node.type); case 157 /* SetAccessor */: - return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 156 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: case 154 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: @@ -62611,7 +64617,7 @@ var ts; case 95 /* NullKeyword */: case 131 /* NeverKeyword */: return ts.createVoidZero(); - case 173 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: return serializeTypeNode(node.type); case 163 /* FunctionType */: case 164 /* ConstructorType */: @@ -62626,7 +64632,7 @@ var ts; return ts.createIdentifier("String"); case 135 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 178 /* LiteralType */: + case 180 /* LiteralType */: switch (node.literal.kind) { case 9 /* StringLiteral */: return ts.createIdentifier("String"); @@ -62646,18 +64652,18 @@ var ts; : ts.createIdentifier("Symbol"); case 162 /* TypeReference */: return serializeTypeReferenceNode(node); - case 170 /* IntersectionType */: - case 169 /* UnionType */: + case 172 /* IntersectionType */: + case 171 /* UnionType */: return serializeUnionOrIntersectionType(node); case 165 /* TypeQuery */: - case 175 /* TypeOperator */: - case 176 /* IndexedAccessType */: - case 177 /* MappedType */: + case 177 /* TypeOperator */: + case 178 /* IndexedAccessType */: + case 179 /* MappedType */: case 166 /* TypeLiteral */: case 119 /* AnyKeyword */: case 142 /* UnknownKeyword */: - case 174 /* ThisType */: - case 179 /* ImportType */: + case 176 /* ThisType */: + case 181 /* ImportType */: break; default: return ts.Debug.failBadSyntaxKind(node); @@ -62670,7 +64676,7 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; - while (typeNode.kind === 173 /* ParenthesizedType */) { + while (typeNode.kind === 175 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 131 /* NeverKeyword */) { @@ -62709,14 +64715,14 @@ var ts; * @param node The type reference node. */ function serializeTypeReferenceNode(node) { - var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentScope); + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: - var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); + return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); case ts.TypeReferenceSerializationKind.BooleanType: @@ -62741,14 +64747,35 @@ var ts; return ts.Debug.assertNever(kind); } } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 71 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 71 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } /** * Serializes an entity name as an expression for decorator type metadata. * * @param node The entity name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * entity name at runtime. */ - function serializeEntityNameAsExpression(node, useFallback) { + function serializeEntityNameAsExpression(node) { switch (node.kind) { case 71 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were @@ -62756,13 +64783,10 @@ var ts; var name = ts.getMutableClone(node); name.flags &= ~8 /* Synthesized */; name.original = undefined; - 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); - } + name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. return name; case 146 /* QualifiedName */: - return serializeQualifiedNameAsExpression(node, useFallback); + return serializeQualifiedNameAsExpression(node); } } /** @@ -62772,19 +64796,8 @@ var ts; * @param useFallback A value indicating whether to use logical operators to test for the * qualified name at runtime. */ - function serializeQualifiedNameAsExpression(node, useFallback) { - var left; - if (node.left.kind === 71 /* Identifier */) { - left = serializeEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); - } - else { - left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); - } - return ts.createPropertyAccess(left, node.right); + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); } /** * Gets an expression that points to the global "Symbol" constructor at runtime if it is @@ -63090,7 +65103,7 @@ var ts; // elide statement if there are no initialized variables. return undefined; } - return ts.setTextRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } else { return ts.visitEachChild(node, visitor, context); @@ -63171,7 +65184,7 @@ var ts; * @param node The enum declaration node. */ function shouldEmitEnumDeclaration(node) { - return !ts.isConst(node) + return !ts.isEnumConst(node) || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } @@ -63193,9 +65206,10 @@ var ts; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. - if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; } } @@ -63220,7 +65234,7 @@ var ts; // x[x["y"] = 0] = "y"; // ... // })(x || (x = {})); - var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, @@ -63228,8 +65242,13 @@ var ts; /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } ts.setTextRange(enumStatement, node); - ts.setEmitFlags(enumStatement, emitFlags); + ts.addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); // Add a DeclarationMarker for the enum to preserve trailing comments and mark // the end of the declaration. @@ -63247,7 +65266,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -63268,7 +65287,7 @@ var ts; var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); - return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); + return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); } /** * Transforms the value of an enum member. @@ -63346,12 +65365,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentScope.kind === 274 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 277 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 238 /* EnumDeclaration */) { + if (node.kind === 241 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -63376,7 +65395,7 @@ var ts; // })(m1 || (m1 = {})); // trailing comment module // ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(statement); return true; } @@ -63411,9 +65430,10 @@ var ts; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. - if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; } } @@ -63437,7 +65457,7 @@ var ts; // (function (x_1) { // x_1.y = ...; // })(x || (x = {})); - var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, @@ -63445,8 +65465,13 @@ var ts; /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } ts.setTextRange(moduleStatement, node); - ts.setEmitFlags(moduleStatement, emitFlags); + ts.addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); // Add a DeclarationMarker for the namespace to preserve trailing comments and mark // the end of the declaration. @@ -63470,7 +65495,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 240 /* ModuleBlock */) { + if (body.kind === 243 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -63488,7 +65513,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -63516,13 +65541,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 240 /* ModuleBlock */) { + if (body.kind !== 243 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 239 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -63563,7 +65588,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 246 /* NamespaceImport */) { + if (node.kind === 249 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -63718,17 +65743,17 @@ var ts; * Creates a statement for the provided expression. This is used in calls to `map`. */ function expressionToStatement(expression) { - return ts.createStatement(expression); + return ts.createExpressionStatement(expression); } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); - var statement = ts.createStatement(expression); + var statement = ts.createExpressionStatement(expression); ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { - return ts.setTextRange(ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); + return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); } function createNamespaceExportExpression(exportName, exportValue, location) { return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); @@ -63795,16 +65820,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(271 /* ShorthandPropertyAssignment */); + context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(239 /* ModuleDeclaration */); + context.enableEmitNotification(242 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 239 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 242 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 238 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 241 /* EnumDeclaration */; } /** * Hook for node emit. @@ -63865,9 +65890,9 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -63905,9 +65930,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 274 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 239 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 238 /* EnumDeclaration */); + if (container && container.kind !== 277 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 242 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 241 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -64042,15 +66067,15 @@ var ts; case 120 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 197 /* AwaitExpression */: + case 199 /* AwaitExpression */: return visitAwaitExpression(node); case 154 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: return visitArrowFunction(node); default: return ts.visitEachChild(node, visitor, context); @@ -64059,27 +66084,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 213 /* Block */: - case 227 /* SwitchStatement */: - case 241 /* CaseBlock */: - case 266 /* CaseClause */: - case 267 /* DefaultClause */: - case 230 /* TryStatement */: - case 218 /* DoStatement */: - case 219 /* WhileStatement */: - case 217 /* IfStatement */: - case 226 /* WithStatement */: - case 228 /* LabeledStatement */: + case 216 /* Block */: + case 230 /* SwitchStatement */: + case 244 /* CaseBlock */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + case 233 /* TryStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 220 /* IfStatement */: + case 229 /* WithStatement */: + case 231 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -64114,7 +66139,7 @@ var ts; function visitVariableStatementInAsyncBody(node) { if (isVariableDeclarationListWithCollidingName(node.declarationList)) { var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); - return expression ? ts.createStatement(expression) : undefined; + return expression ? ts.createExpressionStatement(expression) : undefined; } return ts.visitEachChild(node, visitor, context); } @@ -64280,7 +66305,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 193 /* ArrowFunction */; + var isArrowFunction = node.kind === 195 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -64298,7 +66323,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -64353,11 +66378,11 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(187 /* CallExpression */); - context.enableSubstitution(185 /* PropertyAccessExpression */); - context.enableSubstitution(186 /* ElementAccessExpression */); + context.enableSubstitution(189 /* CallExpression */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(188 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(235 /* ClassDeclaration */); + context.enableEmitNotification(238 /* ClassDeclaration */); context.enableEmitNotification(154 /* MethodDeclaration */); context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); @@ -64401,11 +66426,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 187 /* CallExpression */: + case 189 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -64437,7 +66462,7 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 235 /* ClassDeclaration */ + return kind === 238 /* ClassDeclaration */ || kind === 155 /* Constructor */ || kind === 154 /* MethodDeclaration */ || kind === 156 /* GetAccessor */ @@ -64536,25 +66561,25 @@ var ts; return node; } switch (node.kind) { - case 197 /* AwaitExpression */: + case 199 /* AwaitExpression */: return visitAwaitExpression(node); - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: return visitYieldExpression(node); - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitReturnStatement(node); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node); - case 196 /* VoidExpression */: + case 198 /* VoidExpression */: return visitVoidExpression(node); case 155 /* Constructor */: return visitConstructorDeclaration(node); @@ -64564,19 +66589,19 @@ var ts; return visitGetAccessorDeclaration(node); case 157 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: return visitArrowFunction(node); case 149 /* Parameter */: return visitParameter(node); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return visitExpressionStatement(node); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -64610,7 +66635,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 222 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 225 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); @@ -64622,7 +66647,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 272 /* SpreadAssignment */) { + if (e.kind === 275 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -64631,7 +66656,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 270 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 273 /* PropertyAssignment */ ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -64649,7 +66674,7 @@ var ts; // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 184 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 186 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -64788,13 +66813,13 @@ var ts; return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ ts.createPropertyAssignment("error", catchVariable) ]))) ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -64905,7 +66930,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -64933,7 +66958,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependStatements(statements, leadingStatements); + ts.addStatementsAfterPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -64962,11 +66987,11 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(187 /* CallExpression */); - context.enableSubstitution(185 /* PropertyAccessExpression */); - context.enableSubstitution(186 /* ElementAccessExpression */); + context.enableSubstitution(189 /* CallExpression */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(188 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(235 /* ClassDeclaration */); + context.enableEmitNotification(238 /* ClassDeclaration */); context.enableEmitNotification(154 /* MethodDeclaration */); context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); @@ -65010,11 +67035,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 187 /* CallExpression */: + case 189 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -65046,7 +67071,7 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 235 /* ClassDeclaration */ + return kind === 238 /* ClassDeclaration */ || kind === 155 /* Constructor */ || kind === 154 /* MethodDeclaration */ || kind === 156 /* GetAccessor */ @@ -65068,7 +67093,7 @@ var ts; name: "typescript:assign", scoped: false, priority: 1, - text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };" + text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };" }; function createAssignHelper(context, attributesSegments) { if (context.getCompilerOptions().target >= 2 /* ES2015 */) { @@ -65159,13 +67184,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 255 /* JsxElement */: + case 258 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 256 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 259 /* JsxFragment */: + case 262 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 265 /* JsxExpression */: + case 268 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -65175,13 +67200,13 @@ var ts; switch (node.kind) { case 10 /* JsxText */: return visitJsxText(node); - case 265 /* JsxExpression */: + case 268 /* JsxExpression */: return visitJsxExpression(node); - case 255 /* JsxElement */: + case 258 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 256 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 259 /* JsxFragment */: + case 262 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -65256,7 +67281,7 @@ var ts; literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); return ts.setTextRange(literal, node); } - else if (node.kind === 265 /* JsxExpression */) { + else if (node.kind === 268 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } @@ -65350,7 +67375,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 255 /* JsxElement */) { + if (node.kind === 258 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -65656,7 +67681,7 @@ var ts; return node; } switch (node.kind) { - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -65889,13 +67914,13 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 225 /* ReturnStatement */ + && node.kind === 228 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 213 /* Block */))) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } @@ -65923,63 +67948,63 @@ var ts; switch (node.kind) { case 115 /* StaticKeyword */: return undefined; // elide static keyword - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: return visitClassExpression(node); case 149 /* Parameter */: return visitParameter(node); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: return visitArrowFunction(node); - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitVariableDeclaration(node); case 71 /* Identifier */: return visitIdentifier(node); - case 233 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitSwitchStatement(node); - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: return visitCaseBlock(node); - case 213 /* Block */: + case 216 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 224 /* BreakStatement */: - case 223 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); - case 218 /* DoStatement */: - case 219 /* WhileStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return visitExpressionStatement(node); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClause(node); - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); case 147 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 187 /* CallExpression */: + case 189 /* CallExpression */: return visitCallExpression(node); - case 188 /* NewExpression */: + case 190 /* NewExpression */: return visitNewExpression(node); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); case 13 /* NoSubstitutionTemplateLiteral */: case 14 /* TemplateHead */: @@ -65990,28 +68015,28 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 202 /* TemplateExpression */: + case 204 /* TemplateExpression */: return visitTemplateExpression(node); - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: return visitYieldExpression(node); - case 204 /* SpreadElement */: + case 206 /* SpreadElement */: return visitSpreadElement(node); case 97 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 99 /* ThisKeyword */: return visitThisKeyword(node); - case 210 /* MetaProperty */: + case 212 /* MetaProperty */: return visitMetaProperty(node); case 154 /* MethodDeclaration */: return visitMethodDeclaration(node); case 156 /* GetAccessor */: case 157 /* SetAccessor */: return visitAccessorDeclaration(node); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -66028,7 +68053,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -66098,14 +68123,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 224 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 227 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 224 /* BreakStatement */) { + if (node.kind === 227 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -66116,7 +68141,7 @@ var ts; } } else { - if (node.kind === 224 /* BreakStatement */) { + if (node.kind === 227 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -66233,7 +68258,7 @@ var ts; if (node.name) { enableSubstitutionsForBlockScopedBindings(); } - var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var classFunction = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -66283,7 +68308,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -66297,7 +68322,7 @@ var ts; */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), + statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), /*location*/ extendsClauseElement)); } } @@ -66396,7 +68421,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -66416,11 +68441,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 225 /* ReturnStatement */) { + if (statement.kind === 228 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 217 /* IfStatement */) { + else if (statement.kind === 220 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -66428,7 +68453,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 213 /* Block */) { + else if (statement.kind === 216 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -66486,7 +68511,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 216 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -66496,8 +68521,8 @@ var ts; && statementOffset === ctorStatements.length - 1 && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 200 /* BinaryExpression */ - || superCallExpression.left.kind !== 187 /* CallExpression */) { + if (superCallExpression.kind !== 202 /* BinaryExpression */ + || superCallExpression.left.kind !== 189 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -66506,7 +68531,7 @@ var ts; return 2 /* ReplaceWithReturn */; } // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis(), firstStatement); + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); // If we're actually replacing the original statement, we need to signal this to the caller. if (superCallExpression) { return 1 /* ReplaceSuperCapture */; @@ -66612,7 +68637,7 @@ var ts; /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); } } /** @@ -66626,7 +68651,7 @@ var ts; function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ - ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); @@ -66678,7 +68703,7 @@ var ts; var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ - ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 ? temp : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), /*location*/ parameter)) @@ -66694,11 +68719,11 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 193 /* ArrowFunction */) { + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } - function captureThisForNode(statements, node, initializer, originalStatement) { + function captureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -66706,7 +68731,6 @@ var ts; /*type*/ undefined, initializer) ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); - ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); } @@ -66714,7 +68738,7 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: return statements; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: @@ -66728,8 +68752,8 @@ var ts; // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); @@ -66760,7 +68784,7 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 212 /* SemicolonClassElement */: + case 215 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; case 154 /* MethodDeclaration */: @@ -66804,7 +68828,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); ts.setEmitFlags(memberFunction, 1536 /* NoComments */); ts.setSourceMapRange(memberFunction, sourceMapRange); - var statement = ts.setTextRange(ts.createStatement(ts.createAssignment(memberName, memberFunction)), + var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), /*location*/ member); ts.setOriginalNode(statement, member); ts.setCommentRange(statement, commentRange); @@ -66822,7 +68846,7 @@ var ts; * @param accessors The set of related get/set accessors. */ function transformAccessorsToStatement(receiver, accessors, container) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); + var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); // The location for the statement is used to emit source maps only. // No comments should be emitted for this statement to align with the // old emitter. @@ -66965,7 +68989,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 234 /* FunctionDeclaration */ || node.kind === 192 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 237 /* FunctionDeclaration */ || node.kind === 194 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -67010,7 +69034,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 193 /* ArrowFunction */); + ts.Debug.assert(node.kind === 195 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -67036,7 +69060,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependStatements(statements, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { @@ -67078,10 +69102,10 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 191 /* ParenthesizedExpression */: - return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 200 /* BinaryExpression */: - return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + case 193 /* ParenthesizedExpression */: + return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 202 /* BinaryExpression */: + return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); } @@ -67099,9 +69123,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -67143,7 +69167,7 @@ var ts; } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); + updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -67298,18 +69322,18 @@ var ts; var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) - : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement), node, convertedLoopState && resetLabel); + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 218 /* DoStatement */: - case 219 /* WhileStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -67367,11 +69391,11 @@ var ts; var assignment = ts.createAssignment(initializer, boundValue); if (ts.isDestructuringAssignment(assignment)) { ts.aggregateTransformFlags(assignment); - statements.push(ts.createStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); + statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); } else { assignment.end = initializer.end; - statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); + statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); } } if (convertedLoopBodyStatements) { @@ -67460,13 +69484,13 @@ var ts; return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ ts.createPropertyAssignment("error", catchVariable) ]))) ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -67565,11 +69589,11 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 233 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 236 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -67615,7 +69639,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependStatements(statements_4, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -67733,7 +69757,7 @@ var ts; function copyOutParameters(outParams, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); } } function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { @@ -67750,7 +69774,7 @@ var ts; ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { - statements.push(ts.createStatement(callResult)); + statements.push(ts.createExpressionStatement(callResult)); copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); } else { @@ -67859,10 +69883,10 @@ var ts; case 154 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -68114,7 +70138,7 @@ var ts; statements.push(funcStatements[classBodyStart]); classBodyStart++; // Add the class alias following the declaration. - statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); } // Find the trailing 'return' statement (4) while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { @@ -68251,7 +70275,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 183 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -68518,9 +70542,9 @@ var ts; context.enableEmitNotification(154 /* MethodDeclaration */); context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); - context.enableEmitNotification(193 /* ArrowFunction */); - context.enableEmitNotification(192 /* FunctionExpression */); - context.enableEmitNotification(234 /* FunctionDeclaration */); + context.enableEmitNotification(195 /* ArrowFunction */); + context.enableEmitNotification(194 /* FunctionExpression */); + context.enableEmitNotification(237 /* FunctionDeclaration */); } } /** @@ -68561,10 +70585,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 182 /* BindingElement */: - case 235 /* ClassDeclaration */: - case 238 /* EnumDeclaration */: - case 232 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 235 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -68646,11 +70670,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 216 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 187 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -68658,7 +70682,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 204 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -68686,7 +70710,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -68711,15 +70735,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(257 /* JsxOpeningElement */); - context.enableEmitNotification(258 /* JsxClosingElement */); - context.enableEmitNotification(256 /* JsxSelfClosingElement */); + context.enableEmitNotification(260 /* JsxOpeningElement */); + context.enableEmitNotification(261 /* JsxClosingElement */); + context.enableEmitNotification(259 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(185 /* PropertyAccessExpression */); - context.enableSubstitution(270 /* PropertyAssignment */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(273 /* PropertyAssignment */); return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -68738,9 +70762,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 257 /* JsxOpeningElement */: - case 258 /* JsxClosingElement */: - case 256 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 261 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -69072,13 +71096,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 218 /* DoStatement */: + case 221 /* DoStatement */: return visitDoStatement(node); - case 219 /* WhileStatement */: + case 222 /* WhileStatement */: return visitWhileStatement(node); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitSwitchStatement(node); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -69091,24 +71115,24 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); case 156 /* GetAccessor */: case 157 /* SetAccessor */: return visitAccessorDeclaration(node); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node); - case 224 /* BreakStatement */: + case 227 /* BreakStatement */: return visitBreakStatement(node); - case 223 /* ContinueStatement */: + case 226 /* ContinueStatement */: return visitContinueStatement(node); - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitReturnStatement(node); default: if (node.transformFlags & 16777216 /* ContainsYield */) { @@ -69129,21 +71153,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node); - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return visitConditionalExpression(node); - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: return visitYieldExpression(node); - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 187 /* CallExpression */: + case 189 /* CallExpression */: return visitCallExpression(node); - case 188 /* NewExpression */: + case 190 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -69156,9 +71180,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -69290,7 +71314,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -69334,7 +71358,7 @@ var ts; if (variables.length === 0) { return undefined; } - return ts.setSourceMapRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } } /** @@ -69386,7 +71410,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -69398,7 +71422,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -69522,7 +71546,7 @@ var ts; } else { if (containsYield(node) && pendingExpressions.length > 0) { - emitWorker(1 /* Statement */, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); + emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]); pendingExpressions = []; } pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); @@ -69675,7 +71699,7 @@ var ts; return ts.inlineExpressions(expressions); function reduceProperty(expressions, property) { if (containsYield(property) && expressions.length > 0) { - emitStatement(ts.createStatement(ts.inlineExpressions(expressions))); + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions))); expressions = []; } var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); @@ -69774,35 +71798,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 213 /* Block */: + case 216 /* Block */: return transformAndEmitBlock(node); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 217 /* IfStatement */: + case 220 /* IfStatement */: return transformAndEmitIfStatement(node); - case 218 /* DoStatement */: + case 221 /* DoStatement */: return transformAndEmitDoStatement(node); - case 219 /* WhileStatement */: + case 222 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return transformAndEmitForStatement(node); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 223 /* ContinueStatement */: + case 226 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 224 /* BreakStatement */: + case 227 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 226 /* WithStatement */: + case 229 /* WithStatement */: return transformAndEmitWithStatement(node); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 229 /* ThrowStatement */: + case 232 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 230 /* TryStatement */: + case 233 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -69839,7 +71863,7 @@ var ts; pendingExpressions.push(transformInitializedVariable(variable)); } if (pendingExpressions.length) { - emitStatement(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); variablesWritten += pendingExpressions.length; pendingExpressions = []; } @@ -69990,7 +72014,7 @@ var ts; transformAndEmitVariableDeclarationList(initializer); } else { - emitStatement(ts.setTextRange(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); } } markLabel(conditionLabel); @@ -70000,7 +72024,7 @@ var ts; transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); if (node.incrementor) { - emitStatement(ts.setTextRange(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); } emitBreak(conditionLabel); endLoopBlock(); @@ -70061,7 +72085,7 @@ var ts; var initializer = node.initializer; hoistVariableDeclaration(keysIndex); emitAssignment(keysArray, ts.createArrayLiteral()); - emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, ts.createLiteral(0)); var conditionLabel = defineLabel(); @@ -70084,7 +72108,7 @@ var ts; emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); - emitStatement(ts.createStatement(ts.createPostfixIncrement(keysIndex))); + emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex))); emitBreak(conditionLabel); endLoopBlock(); } @@ -70232,7 +72256,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 267 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 270 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -70245,7 +72269,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 266 /* CaseClause */) { + if (clause.kind === 269 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -71108,7 +73132,7 @@ var ts; // indicate entry into a protected region by pushing the label numbers // for each block in the protected region. var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; - statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), /*typeArguments*/ undefined, [ ts.createArrayLiteral([ createLabel(startLabel), @@ -71122,7 +73146,7 @@ var ts; if (markLabelEnd) { // The case clause for the last label falls through to this label, so we // add an assignment statement to reflect the change in labels. - statements.push(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); } } clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); @@ -71280,7 +73304,7 @@ var ts; * @param operationLocation The source map location for the operation. */ function writeAssign(left, right, operationLocation) { - writeStatement(ts.setTextRange(ts.createStatement(ts.createAssignment(left, right)), operationLocation)); + writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation)); } /** * Writes a Throw operation to the current label's statement list. @@ -71474,11 +73498,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(200 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(198 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(199 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(271 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(274 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -71528,7 +73552,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -71571,7 +73595,7 @@ var ts; // // define(moduleName?, ["module1", "module2"], function ... var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(define, + ts.createExpressionStatement(ts.createCall(define, /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ // Add the dependency array argument: // @@ -71622,9 +73646,9 @@ var ts; ts.createIdentifier("exports") ])) ]), - 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.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(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"), + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), @@ -71648,7 +73672,7 @@ var ts; // } // })(function ...) var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(umdHeader, + ts.createExpressionStatement(ts.createCall(umdHeader, /*typeArguments*/ undefined, [ // Add the module body function argument: // @@ -71727,7 +73751,7 @@ var ts; if (expr === name) { return undefined; } - return ts.createStatement(ts.createAssignment(name, expr)); + return ts.createExpressionStatement(ts.createAssignment(name, expr)); } /** * Transforms a SourceFile into an AMD or UMD module body. @@ -71751,7 +73775,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -71782,7 +73806,7 @@ var ts; statements.push(statement); } else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); ts.setTextRange(statement, currentModuleInfo.exportEquals); ts.setEmitFlags(statement, 1536 /* NoComments */); statements.push(statement); @@ -71800,23 +73824,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitImportDeclaration(node); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return visitExportDeclaration(node); - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 303 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 304 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -71843,17 +73867,17 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 272 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } @@ -71947,7 +73971,7 @@ var ts; ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) ]; var body = ts.createBlock([ - ts.createStatement(ts.createCall(ts.createIdentifier("require"), + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) ]); var func; @@ -72042,7 +74066,7 @@ var ts; if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { // import "mod"; - return ts.setTextRange(ts.createStatement(createRequireCall(node)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); } else { var variables = []; @@ -72063,18 +74087,20 @@ var ts; /*type*/ undefined, ts.getGeneratedNameForNode(node))); } } - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), - /*location*/ node)); + /*location*/ node), + /*original*/ node)); } } else if (namespaceDeclaration && ts.isDefaultImport(node)) { // import d, * as n from "mod"; statements = ts.append(statements, ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node)), - /*location*/ node) + /*location*/ node), + /*original*/ node) ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -72110,20 +74136,20 @@ var ts; var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(node.name, createRequireCall(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); } else { - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), /*type*/ undefined, createRequireCall(node)) ], - /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node)); + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); } } else { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); } } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -72152,23 +74178,24 @@ var ts; var statements = []; // export { x, y } from "mod"; if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.setTextRange(ts.createVariableStatement( + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(generatedName, /*type*/ undefined, createRequireCall(node)) ])), - /*location*/ node)); + /*location*/ node), + /* original */ node)); } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.setTextRange(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); } return ts.singleOrMany(statements); } else { // export * from "mod"; - return ts.setTextRange(ts.createStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); } } /** @@ -72274,7 +74301,7 @@ var ts; statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); } if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); } } else { @@ -72335,7 +74362,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 214 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -72390,10 +74417,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 246 /* NamespaceImport */: + case 249 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 247 /* NamedImports */: + case 250 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -72523,10 +74550,10 @@ var ts; function createUnderscoreUnderscoreESModule() { var statement; if (languageVersion === 0 /* ES3 */) { - statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); + statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); } else { - statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ ts.createIdentifier("exports"), ts.createLiteral("__esModule"), @@ -72547,7 +74574,7 @@ var ts; * @param allowComments An optional value indicating whether to emit comments for the statement. */ function createExportStatement(name, value, location, allowComments) { - var statement = ts.setTextRange(ts.createStatement(createExportExpression(name, value)), location); + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); ts.startOnNewLine(statement); if (!allowComments) { ts.setEmitFlags(statement, 1536 /* NoComments */); @@ -72592,7 +74619,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 274 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -72656,10 +74683,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return substituteBinaryExpression(node); - case 199 /* PostfixUnaryExpression */: - case 198 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -72680,7 +74707,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 274 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -72755,7 +74782,7 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 199 /* PostfixUnaryExpression */ + var expression = node.kind === 201 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; @@ -72831,11 +74858,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(271 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(200 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(198 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(199 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(274 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -72897,7 +74924,7 @@ var ts; var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction])) @@ -73020,7 +75047,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -73056,7 +75083,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 250 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 253 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -73081,7 +75108,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 250 /* ExportDeclaration */) { + if (externalImport.kind !== 253 /* ExportDeclaration */) { continue; } if (!externalImport.exportClause) { @@ -73135,9 +75162,9 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, /*type*/ undefined) ]), m, ts.createBlock([ - ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) ])), - ts.createStatement(ts.createCall(exportFunction, + ts.createExpressionStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exports])) ], /*multiline*/ true)); } @@ -73159,19 +75186,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local - statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -73187,7 +75214,7 @@ var ts; var e = _d[_c]; properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); } - statements.push(ts.createStatement(ts.createCall(exportFunction, + statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); } else { @@ -73196,7 +75223,7 @@ var ts; // emit as: // // exportStar(foo_1_1); - statements.push(ts.createStatement(ts.createCall(exportStarFunction, + statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, /*typeArguments*/ undefined, [parameterName]))); } break; @@ -73221,15 +75248,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitImportDeclaration(node); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -73330,7 +75357,7 @@ var ts; var name = ts.getLocalName(node); hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -73367,7 +75394,7 @@ var ts; } var statements; if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); } if (isMarkedDeclaration) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -73405,7 +75432,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 274 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 277 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -73469,7 +75496,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 214 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -73531,10 +75558,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 246 /* NamespaceImport */: + case 249 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 247 /* NamedImports */: + case 250 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -73686,7 +75713,7 @@ var ts; * @param allowComments An optional value indicating whether to emit comments for the statement. */ function createExportStatement(name, value, allowComments) { - var statement = ts.createStatement(createExportExpression(name, value)); + var statement = ts.createExpressionStatement(createExportExpression(name, value)); ts.startOnNewLine(statement); if (!allowComments) { ts.setEmitFlags(statement, 1536 /* NoComments */); @@ -73714,43 +75741,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node); - case 218 /* DoStatement */: + case 221 /* DoStatement */: return visitDoStatement(node); - case 219 /* WhileStatement */: + case 222 /* WhileStatement */: return visitWhileStatement(node); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); - case 226 /* WithStatement */: + case 229 /* WithStatement */: return visitWithStatement(node); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitSwitchStatement(node); - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: return visitCaseBlock(node); - case 266 /* CaseClause */: + case 269 /* CaseClause */: return visitCaseClause(node); - case 267 /* DefaultClause */: + case 270 /* DefaultClause */: return visitDefaultClause(node); - case 230 /* TryStatement */: + case 233 /* TryStatement */: return visitTryStatement(node); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClause(node); - case 213 /* Block */: + case 216 /* Block */: return visitBlock(node); - case 303 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 304 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -73933,7 +75960,7 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 200 /* BinaryExpression */) { + && node.kind === 202 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { @@ -73998,7 +76025,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 274 /* SourceFile */; + return container !== undefined && container.kind === 277 /* SourceFile */; } else { return false; @@ -74031,7 +76058,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 274 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -74079,7 +76106,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -74115,10 +76142,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return substituteBinaryExpression(node); - case 198 /* PrefixUnaryExpression */: - case 199 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -74211,14 +76238,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 199 /* PostfixUnaryExpression */ + var expression = node.kind === 201 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 199 /* PostfixUnaryExpression */) { + if (node.kind === 201 /* PostfixUnaryExpression */) { expression = node.operator === 43 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); @@ -74240,7 +76267,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 274 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -74279,7 +76306,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(274 /* SourceFile */); + context.enableEmitNotification(277 /* SourceFile */); context.enableSubstitution(71 /* Identifier */); var currentSourceFile; return ts.chainBundle(transformSourceFile); @@ -74308,10 +76335,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -74418,7 +76445,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 235 /* ClassDeclaration */) { + else if (node.parent.kind === 238 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -74447,7 +76474,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 235 /* ClassDeclaration */) { + else if (node.parent.kind === 238 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -74494,7 +76521,7 @@ var ts; return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 232 /* VariableDeclaration */ || node.kind === 182 /* BindingElement */) { + if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -74513,7 +76540,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 235 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) { + else if (node.parent.kind === 238 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -74604,7 +76631,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 235 /* ClassDeclaration */) { + else if (node.parent.kind === 238 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -74618,7 +76645,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -74674,7 +76701,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 235 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -74687,7 +76714,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: case 163 /* FunctionType */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -74702,10 +76729,10 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; case 159 /* ConstructSignature */: @@ -74719,17 +76746,17 @@ var ts; if (ts.hasModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 235 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -74744,7 +76771,7 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 235 /* ClassDeclaration */) { + if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : @@ -74794,7 +76821,8 @@ var ts; 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | - 4 /* GenerateNamesForShadowedTypeParams */; + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; /** * Transforms a ts file into a .d.ts file * This process requires type information, which is retrieved through the emit resolver. Because of this, @@ -74814,6 +76842,7 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, @@ -74822,6 +76851,7 @@ var ts; reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode }; var errorNameNode; var currentSourceFile; @@ -74836,12 +76866,18 @@ var ts; return; } necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); - for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) { - var ref = typeReferenceDirectives_1[_i]; + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; necessaryTypeRefernces.set(ref, true); } } - function trackReferencedAmbientModule(node) { + function trackReferencedAmbientModule(node, symbol) { + // If it is visible via `// `, then we should just use that + var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */); + if (ts.length(directives)) { + return recordTypeReferenceDirectivesIfNecessary(directives); + } + // Otherwise we should emit a path-based reference var container = ts.getSourceFileOfNode(node); refs.set("" + ts.getOriginalNodeId(container), container); } @@ -74874,6 +76910,11 @@ var ts; } } } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } function trackSymbol(symbol, enclosingDeclaration, meaning) { if (symbol.flags & 262144 /* TypeParameter */) return; @@ -74896,12 +76937,12 @@ var ts; } } function transformRoot(node) { - if (node.kind === 274 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { return node; } - if (node.kind === 275 /* Bundle */) { + if (node.kind === 278 /* Bundle */) { isBundledEmit = true; - var refs_1 = ts.createMap(); + refs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) @@ -74915,7 +76956,7 @@ var ts; getSymbolAccessibilityDiagnostic = throwDiagnostic; needsScopeFixMarker = false; resultHasScopeMarker = false; - collectReferences(sourceFile, refs_1); + collectReferences(sourceFile, refs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -74927,8 +76968,8 @@ var ts; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 277 /* InputFiles */) { - return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapText); + if (prepend.kind === 280 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); } })); bundle.syntheticFileReferences = []; @@ -74936,7 +76977,7 @@ var ts; bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); - refs_1.forEach(referenceVisitor_1); + refs.forEach(referenceVisitor_1); return bundle; } // Single source file @@ -74964,6 +77005,7 @@ var ts; combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; function getFileReferencesForUsedTypeReferences() { return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; @@ -75025,7 +77067,7 @@ var ts; return name; } else { - if (name.kind === 181 /* ArrayBindingPattern */) { + if (name.kind === 183 /* ArrayBindingPattern */) { return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -75033,7 +77075,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 206 /* OmittedExpression */) { + if (elem.kind === 208 /* OmittedExpression */) { return elem; } return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -75091,7 +77133,7 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 232 /* VariableDeclaration */ || node.kind === 182 /* BindingElement */) { + if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } if (node.kind === 149 /* Parameter */ @@ -75113,20 +77155,20 @@ var ts; function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 234 /* FunctionDeclaration */: - case 239 /* ModuleDeclaration */: - case 236 /* InterfaceDeclaration */: - case 235 /* ClassDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 238 /* EnumDeclaration */: + case 237 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 239 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 243 /* ImportEqualsDeclaration */: - case 244 /* ImportDeclaration */: - case 250 /* ExportDeclaration */: - case 249 /* ExportAssignment */: + case 246 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: return false; } return false; @@ -75180,11 +77222,19 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 239 /* ModuleDeclaration */ && parent.kind !== 179 /* ImportType */); - if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { - var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); - if (newName) { - return ts.createLiteral(newName); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } } } return input; @@ -75192,7 +77242,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 254 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 257 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return ts.updateImportEqualsDeclaration(decl, @@ -75219,7 +77269,7 @@ var ts; return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 246 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 249 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -75324,14 +77374,14 @@ var ts; checkEntityNameVisibility(input.exprName, enclosingDeclaration); } var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 177 /* MappedType */) && input.parent.kind !== 237 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 179 /* MappedType */) && input.parent.kind !== 240 /* TypeAliasDeclaration */); if (shouldEnterSuppressNewDiagnosticsContextContext) { // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. suppressNewDiagnosticContexts = true; } if (isProcessedComponent(input)) { switch (input.kind) { - case 207 /* ExpressionWithTypeArguments */: { + case 209 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } @@ -75385,7 +77435,7 @@ var ts; return cleanup(ts.updateIndexSignature(input, /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); } - case 232 /* VariableDeclaration */: { + case 235 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -75399,7 +77449,7 @@ var ts; } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 171 /* ConditionalType */: { + case 173 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -75417,7 +77467,7 @@ var ts; case 164 /* ConstructorType */: { return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 179 /* ImportType */: { + case 181 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -75456,7 +77506,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 250 /* ExportDeclaration */: { + case 253 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; resultHasScopeMarker = true; @@ -75465,7 +77515,7 @@ var ts; // Rewrite external module names if necessary return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 249 /* ExportAssignment */: { + case 252 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; @@ -75495,10 +77545,10 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 243 /* ImportEqualsDeclaration */: { + case 246 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 244 /* ImportDeclaration */: { + case 247 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -75519,24 +77569,24 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 237 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 240 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(ts.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 236 /* InterfaceDeclaration */: { + case 239 /* InterfaceDeclaration */: { return cleanup(ts.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 234 /* FunctionDeclaration */: { + case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type return cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); } - case 239 /* ModuleDeclaration */: { + case 242 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 240 /* ModuleBlock */) { + if (inner && inner.kind === 243 /* ModuleBlock */) { var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); needsDeclare = previousNeedsDeclare; @@ -75557,7 +77607,7 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 235 /* ClassDeclaration */: { + case 238 /* ClassDeclaration */: { var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -75597,7 +77647,7 @@ var ts; getSymbolAccessibilityDiagnostic = oldDiag_1; } var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); - var extendsClause_1 = ts.getClassExtendsHeritageClauseElement(input); + var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 @@ -75627,10 +77677,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 214 /* VariableStatement */: { + case 217 /* VariableStatement */: { return cleanup(transformVariableStatement(input, isPrivate)); } - case 238 /* EnumDeclaration */: { + case 241 /* EnumDeclaration */: { return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -75649,7 +77699,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 239 /* ModuleDeclaration */) { + if (input.kind === 242 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -75670,7 +77720,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 206 /* OmittedExpression */) { + if (e.kind === 208 /* OmittedExpression */) { return; } if (e.name) { @@ -75713,6 +77763,15 @@ var ts; } return false; } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } function ensureModifiers(node, privateDeclaration) { var currentFlags = ts.getModifierFlags(node); var newFlags = ensureModifierFlags(node, privateDeclaration); @@ -75724,9 +77783,9 @@ var ts; function ensureModifierFlags(node, privateDeclaration) { var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 274 /* SourceFile */; + var parentIsFile = node.parent.kind === 277 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { - mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; } return maskModifierFlags(node, mask, additions); @@ -75745,7 +77804,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_7 = function (range) { + var _loop_8 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -75759,7 +77818,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_7(range); + _loop_8(range); } } return prop; @@ -75772,7 +77831,7 @@ var ts; } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 236 /* InterfaceDeclaration */) { + if (node.kind === 239 /* InterfaceDeclaration */) { return true; } return false; @@ -75785,6 +77844,11 @@ var ts; if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) } @@ -75801,7 +77865,7 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: case 149 /* Parameter */: @@ -75811,17 +77875,17 @@ var ts; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 234 /* FunctionDeclaration */: - case 239 /* ModuleDeclaration */: - case 243 /* ImportEqualsDeclaration */: - case 236 /* InterfaceDeclaration */: - case 235 /* ClassDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 238 /* EnumDeclaration */: - case 214 /* VariableStatement */: - case 244 /* ImportDeclaration */: - case 250 /* ExportDeclaration */: - case 249 /* ExportAssignment */: + case 237 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 239 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: + case 217 /* VariableStatement */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: return true; } return false; @@ -75838,14 +77902,14 @@ var ts; case 153 /* MethodSignature */: case 158 /* CallSignature */: case 160 /* IndexSignature */: - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: case 148 /* TypeParameter */: - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: case 162 /* TypeReference */: - case 171 /* ConditionalType */: + case 173 /* ConditionalType */: case 163 /* FunctionType */: case 164 /* ConstructorType */: - case 179 /* ImportType */: + case 181 /* ImportType */: return true; } return false; @@ -75921,7 +77985,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(305 /* Count */); + var enabledSyntaxKindFeatures = new Array(310 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -75968,8 +78032,8 @@ var ts; } }; // Ensure the parse tree is clean before applying transformations - for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { - var node = nodes_3[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } ts.performance.mark("beforeTransform"); @@ -76160,8 +78224,8 @@ var ts; function dispose() { if (state < 3 /* Disposed */) { // Clean up emit nodes on parse tree - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var node = nodes_5[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } // Release references to external entries for GC purposes. @@ -76184,10 +78248,10 @@ var ts; (function (ts) { // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, + emittedLine: 0, + emittedColumn: 0, + sourceLine: 0, + sourceColumn: 0, sourceIndex: 0 }; function createSourceMapWriter(host, writer, compilerOptions) { @@ -76206,9 +78270,6 @@ var ts; var sourceMapData; var sourceMapDataList; var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); - var completedSections; - var sectionStartLine; - var sectionStartColumn; return { initialize: initialize, reset: reset, @@ -76249,9 +78310,6 @@ var ts; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; lastEncodedNameIndex = 0; // Initialize source map data - completedSections = []; - sectionStartLine = 1; - sectionStartColumn = 1; sourceMapData = { sourceMapFilePath: sourceMapFilePath, jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, @@ -76262,7 +78320,6 @@ var ts; sourceMapNames: [], sourceMapMappings: "", sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, - sourceMapDecodedMappings: [] }; // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the // relative paths of the sources list in the sourcemap @@ -76272,10 +78329,10 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 274 /* SourceFile */) { // emitting single module file + if (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { // The relative paths are relative to the common directory @@ -76312,9 +78369,6 @@ var ts; lastEncodedNameIndex = undefined; sourceMapData = undefined; sourceMapDataList = undefined; - completedSections = undefined; - sectionStartLine = undefined; - sectionStartColumn = undefined; } function captureSection() { return { @@ -76327,30 +78381,15 @@ var ts; sourcesContent: sourceMapData.sourceMapSourcesContent, }; } - function resetSectionalData() { - sourceMapData.sourceMapSources = []; - sourceMapData.sourceMapNames = []; - sourceMapData.sourceMapMappings = ""; - sourceMapData.sourceMapSourcesContent = compilerOptions.inlineSources ? [] : undefined; - } - function generateMap() { - if (completedSections.length) { - captureSectionalSpanIfNeeded(/*reset*/ false); - return { - version: 3, - file: sourceMapData.sourceMapFile, - sections: completedSections - }; - } - else { - return captureSection(); - } - } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { return; } + ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); + ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); + ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); + ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; // Line/Comma delimiters if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { @@ -76364,7 +78403,7 @@ var ts; for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { sourceMapData.sourceMapMappings += ";"; } - prevEncodedEmittedColumn = 1; + prevEncodedEmittedColumn = 0; } // 1. Relative Column 0 based sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); @@ -76381,7 +78420,6 @@ var ts; lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; } lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } /** * Emits a mapping. @@ -76399,11 +78437,8 @@ var ts; ts.performance.mark("beforeSourcemap"); } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); - // Convert the location to be one-based. - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine() - sectionStartLine + 1; - var emittedColumn = emittedLine === 0 ? (writer.getColumn() - sectionStartColumn + 1) : writer.getColumn(); + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); // If this location wasn't recorded or the location in source is going backwards, record the span if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan.emittedLine !== emittedLine || @@ -76433,13 +78468,8 @@ var ts; ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function captureSectionalSpanIfNeeded(reset) { - if (lastRecordedSourceMapSpan && lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { // If we've recorded some spans, save them - completedSections.push({ offset: { line: sectionStartLine - 1, column: sectionStartColumn - 1 }, map: captureSection() }); - if (reset) { - resetSectionalData(); - } - } + function isPossiblySourceMap(x) { + return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources; } /** * Emits a node with possible leading and trailing source maps. @@ -76449,49 +78479,66 @@ var ts; * @param emitCallback The callback used to emit the node. */ function emitNodeWithSourceMap(hint, node, emitCallback) { + var _a; if (disabled || ts.isInJsonFile(node)) { return emitCallback(hint, node); } if (node) { if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { - captureSectionalSpanIfNeeded(/*reset*/ true); var text = node.sourceMapText; var parsed = void 0; try { parsed = JSON.parse(text); } - catch (_a) { + catch (_b) { // empty } - var offset = { line: writer.getLine() - 1, column: writer.getColumn() - 1 }; - completedSections.push(parsed - ? { - offset: offset, - map: parsed - } - : { - offset: offset, - // This is just passes the buck on sourcemaps we don't really understand, instead of issuing an error (which would be difficult this late) - url: "data:application/json;charset=utf-8;base64," + ts.base64encode(ts.sys, text) - }); - var emitResult = emitCallback(hint, node); - sectionStartLine = writer.getLine(); - sectionStartColumn = writer.getColumn(); - lastRecordedSourceMapSpan = undefined; - lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; - return emitResult; + if (!parsed || !isPossiblySourceMap(parsed)) { + return emitCallback(hint, node); + } + var offsetLine = writer.getLine(); + var firstLineColumnOffset = writer.getColumn(); + // First, decode the old component sourcemap + var originalMap = parsed; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var resolvedPathCache = ts.createMap(); + var absolutePathCache = ts.createMap(); + var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap); + for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) { + var pathCacheKey = "" + raw.sourceIndex; + // Apply offsets to each position and fixup source entries + if (!resolvedPathCache.has(pathCacheKey)) { + var rawPath = originalMap.sources[raw.sourceIndex]; + var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath); + var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + resolvedPathCache.set(pathCacheKey, resolvedPath_1); + absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath)); + } + var resolvedPath = resolvedPathCache.get(pathCacheKey); + var absolutePath = absolutePathCache.get(pathCacheKey); + // tslint:disable-next-line:no-null-keyword + setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining? + var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); + // Then reencode all the updated spans into the overall map + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex }); + } + // And actually emit the text these sourcemaps are for + return emitCallback(hint, node); } var emitNode = node.emitNode; var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.sourceMapRange; - var _b = range || node, pos = _b.pos, end = _b.end; + var _d = range || node, pos = _d.pos, end = _d.end; var source = range && range.source; var oldSource = currentSource; if (source === oldSource) source = undefined; if (source) setSourceFile(source); - if (node.kind !== 300 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -76508,7 +78555,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 300 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -76561,20 +78608,25 @@ var ts; if (isJsonSourceMapSource(sourceFile)) { return; } - // Add the file to tsFilePaths - // If sourceroot option: Use the relative path corresponding to the common directory path - // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); + setupSourceEntry(sourceFile.fileName, sourceFile.text); + } + function setupSourceEntry(fileName, content, source) { + if (!source) { + // Add the file to tsFilePaths + // If sourceroot option: Use the relative path corresponding to the common directory path + // otherwise source locations relative to map file location + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(currentSource.fileName); + sourceMapData.inputSourceFileNames.push(fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(currentSource.text); + sourceMapData.sourceMapSourcesContent.push(content); } } } @@ -76586,7 +78638,7 @@ var ts; return undefined; // TODO: GH#18217 } encodeLastRecordedSourceMapSpan(); - return JSON.stringify(generateMap()); + return JSON.stringify(captureSection()); } /** * Gets the SourceMappingURL for the source map. @@ -76682,7 +78734,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 300 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -76696,14 +78748,16 @@ var ts; var savedContainerPos = containerPos; var savedContainerEnd = containerEnd; var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments) { + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. containerPos = pos; } - if (!skipTrailingComments) { + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 233 /* VariableDeclarationList */) { + if (node.kind === 236 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } @@ -77045,20 +79099,20 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 275 /* Bundle */) { + if (sourceFile.kind === 278 /* Bundle */) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error var isJs = ts.isSourceFileJavaScript(sourceFile); - var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } @@ -77113,6 +79167,7 @@ var ts; }); var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; + var exportedModulesFromDeclarationEmit; // Emit each output file ts.performance.mark("beforePrint"); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); @@ -77122,6 +79177,7 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -77180,6 +79236,11 @@ var ts; // Setup and perform the transformation to retrieve declarations from the input files var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { + // Checker wont collect the linked aliases since thats only done when declaration is enabled. + // Do that here when emitting only dts files + nonJsFiles.forEach(collectLinkedAliases); + } var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); if (ts.length(declarationTransform.diagnostics)) { for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { @@ -77204,12 +79265,29 @@ var ts; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } } declarationTransform.dispose(); } + function collectLinkedAliases(node) { + if (ts.isExportAssignment(node)) { + if (node.expression.kind === 71 /* Identifier */) { + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + return; + } + else if (ts.isExportSpecifier(node)) { + resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + return; + } + ts.forEachChild(node, collectLinkedAliases); + } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { - var bundle = sourceFileOrBundle.kind === 275 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 274 /* SourceFile */ ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 278 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 277 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { @@ -77309,9 +79387,9 @@ var ts; break; } switch (node.kind) { - case 274 /* SourceFile */: return printFile(node); - case 275 /* Bundle */: return printBundle(node); - case 276 /* UnparsedSource */: return printUnparsedSource(node); + case 277 /* SourceFile */: return printFile(node); + case 278 /* Bundle */: return printBundle(node); + case 279 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -77456,7 +79534,7 @@ var ts; } return pipelineEmitWithoutComments; case 2 /* SourceMaps */: - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { + if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */) { return pipelineEmitWithSourceMap; } // falls through @@ -77482,7 +79560,7 @@ var ts; pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */); + ts.Debug.assert(hint !== 0 /* SourceFile */); ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { @@ -77501,7 +79579,7 @@ var ts; case 15 /* TemplateMiddle */: case 16 /* TemplateTail */: return emitLiteral(node); - case 276 /* UnparsedSource */: + case 279 /* UnparsedSource */: return emitUnparsedSource(node); // Identifiers case 71 /* Identifier */: @@ -77546,7 +79624,7 @@ var ts; return emitTypeReference(node); case 163 /* FunctionType */: return emitFunctionType(node); - case 284 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: return emitJSDocFunctionType(node); case 164 /* ConstructorType */: return emitConstructorType(node); @@ -77558,178 +79636,181 @@ var ts; return emitArrayType(node); case 168 /* TupleType */: return emitTupleType(node); - case 169 /* UnionType */: + case 169 /* OptionalType */: + return emitOptionalType(node); + case 171 /* UnionType */: return emitUnionType(node); - case 170 /* IntersectionType */: + case 172 /* IntersectionType */: return emitIntersectionType(node); - case 171 /* ConditionalType */: + case 173 /* ConditionalType */: return emitConditionalType(node); - case 172 /* InferType */: + case 174 /* InferType */: return emitInferType(node); - case 173 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: return emitParenthesizedType(node); - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 174 /* ThisType */: + case 176 /* ThisType */: return emitThisType(); - case 175 /* TypeOperator */: + case 177 /* TypeOperator */: return emitTypeOperator(node); - case 176 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 177 /* MappedType */: + case 179 /* MappedType */: return emitMappedType(node); - case 178 /* LiteralType */: + case 180 /* LiteralType */: return emitLiteralType(node); - case 179 /* ImportType */: + case 181 /* ImportType */: return emitImportTypeNode(node); - case 279 /* JSDocAllType */: + case 282 /* JSDocAllType */: write("*"); return; - case 280 /* JSDocUnknownType */: + case 283 /* JSDocUnknownType */: write("?"); return; - case 281 /* JSDocNullableType */: + case 284 /* JSDocNullableType */: return emitJSDocNullableType(node); - case 282 /* JSDocNonNullableType */: + case 285 /* JSDocNonNullableType */: return emitJSDocNonNullableType(node); - case 283 /* JSDocOptionalType */: + case 286 /* JSDocOptionalType */: return emitJSDocOptionalType(node); - case 285 /* JSDocVariadicType */: - return emitJSDocVariadicType(node); + case 170 /* RestType */: + case 288 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); // Binding patterns - case 180 /* ObjectBindingPattern */: + case 182 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 181 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 182 /* BindingElement */: + case 184 /* BindingElement */: return emitBindingElement(node); // Misc - case 211 /* TemplateSpan */: + case 214 /* TemplateSpan */: return emitTemplateSpan(node); - case 212 /* SemicolonClassElement */: + case 215 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 213 /* Block */: + case 216 /* Block */: return emitBlock(node); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return emitVariableStatement(node); - case 215 /* EmptyStatement */: + case 218 /* EmptyStatement */: return emitEmptyStatement(); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return emitExpressionStatement(node); - case 217 /* IfStatement */: + case 220 /* IfStatement */: return emitIfStatement(node); - case 218 /* DoStatement */: + case 221 /* DoStatement */: return emitDoStatement(node); - case 219 /* WhileStatement */: + case 222 /* WhileStatement */: return emitWhileStatement(node); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return emitForStatement(node); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: return emitForInStatement(node); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return emitForOfStatement(node); - case 223 /* ContinueStatement */: + case 226 /* ContinueStatement */: return emitContinueStatement(node); - case 224 /* BreakStatement */: + case 227 /* BreakStatement */: return emitBreakStatement(node); - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: return emitReturnStatement(node); - case 226 /* WithStatement */: + case 229 /* WithStatement */: return emitWithStatement(node); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: return emitSwitchStatement(node); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: return emitLabeledStatement(node); - case 229 /* ThrowStatement */: + case 232 /* ThrowStatement */: return emitThrowStatement(node); - case 230 /* TryStatement */: + case 233 /* TryStatement */: return emitTryStatement(node); - case 231 /* DebuggerStatement */: + case 234 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 233 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return emitClassDeclaration(node); - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: return emitModuleBlock(node); - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: return emitCaseBlock(node); - case 242 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return emitImportDeclaration(node); - case 245 /* ImportClause */: + case 248 /* ImportClause */: return emitImportClause(node); - case 246 /* NamespaceImport */: + case 249 /* NamespaceImport */: return emitNamespaceImport(node); - case 247 /* NamedImports */: + case 250 /* NamedImports */: return emitNamedImports(node); - case 248 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return emitImportSpecifier(node); - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: return emitExportAssignment(node); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return emitExportDeclaration(node); - case 251 /* NamedExports */: + case 254 /* NamedExports */: return emitNamedExports(node); - case 252 /* ExportSpecifier */: + case 255 /* ExportSpecifier */: return emitExportSpecifier(node); - case 253 /* MissingDeclaration */: + case 256 /* MissingDeclaration */: return; // Module references - case 254 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) case 10 /* JsxText */: return emitJsxText(node); - case 257 /* JsxOpeningElement */: - case 260 /* JsxOpeningFragment */: + case 260 /* JsxOpeningElement */: + case 263 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 258 /* JsxClosingElement */: - case 261 /* JsxClosingFragment */: + case 261 /* JsxClosingElement */: + case 264 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 262 /* JsxAttribute */: + case 265 /* JsxAttribute */: return emitJsxAttribute(node); - case 263 /* JsxAttributes */: + case 266 /* JsxAttributes */: return emitJsxAttributes(node); - case 264 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 265 /* JsxExpression */: + case 268 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 266 /* CaseClause */: + case 269 /* CaseClause */: return emitCaseClause(node); - case 267 /* DefaultClause */: + case 270 /* DefaultClause */: return emitDefaultClause(node); - case 268 /* HeritageClause */: + case 271 /* HeritageClause */: return emitHeritageClause(node); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 271 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 272 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 273 /* EnumMember */: + case 276 /* EnumMember */: return emitEnumMember(node); // JSDoc nodes (ignored) // Transformation nodes (ignored) @@ -77764,71 +79845,71 @@ var ts; writeTokenNode(node, writeKeyword); return; // Expressions - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 187 /* CallExpression */: + case 189 /* CallExpression */: return emitCallExpression(node); - case 188 /* NewExpression */: + case 190 /* NewExpression */: return emitNewExpression(node); - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 190 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: return emitFunctionExpression(node); - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: return emitArrowFunction(node); - case 194 /* DeleteExpression */: + case 196 /* DeleteExpression */: return emitDeleteExpression(node); - case 195 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 196 /* VoidExpression */: + case 198 /* VoidExpression */: return emitVoidExpression(node); - case 197 /* AwaitExpression */: + case 199 /* AwaitExpression */: return emitAwaitExpression(node); - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return emitBinaryExpression(node); - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return emitConditionalExpression(node); - case 202 /* TemplateExpression */: + case 204 /* TemplateExpression */: return emitTemplateExpression(node); - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: return emitYieldExpression(node); - case 204 /* SpreadElement */: + case 206 /* SpreadElement */: return emitSpreadExpression(node); - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: return emitClassExpression(node); - case 206 /* OmittedExpression */: + case 208 /* OmittedExpression */: return; - case 208 /* AsExpression */: + case 210 /* AsExpression */: return emitAsExpression(node); - case 209 /* NonNullExpression */: + case 211 /* NonNullExpression */: return emitNonNullExpression(node); - case 210 /* MetaProperty */: + case 212 /* MetaProperty */: return emitMetaProperty(node); // JSX - case 255 /* JsxElement */: + case 258 /* JsxElement */: return emitJsxElement(node); - case 256 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 259 /* JsxFragment */: + case 262 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 301 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 302 /* CommaListExpression */: + case 307 /* CommaListExpression */: return emitCommaList(node); } } @@ -77845,7 +79926,7 @@ var ts; } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 275 /* Bundle */ ? node : undefined; + var bundle = node.kind === 278 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -77971,7 +80052,7 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 284 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 287 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -78140,7 +80221,7 @@ var ts; writePunctuation("["); writePunctuation("]"); } - function emitJSDocVariadicType(node) { + function emitRestOrJSDocVariadicType(node) { write("..."); emit(node.type); } @@ -78149,6 +80230,10 @@ var ts; emitList(node, node.elementTypes, 272 /* TupleTypeElements */); writePunctuation("]"); } + function emitOptionalType(node) { + emit(node.type); + write("?"); + } function emitUnionType(node) { emitList(node, node.types, 260 /* UnionTypeConstituents */); } @@ -78430,7 +80515,7 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 198 /* PrefixUnaryExpression */ + return operand.kind === 200 /* PrefixUnaryExpression */ && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); } @@ -78550,7 +80635,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node); emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 217 /* IfStatement */) { + if (node.elseStatement.kind === 220 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -78621,7 +80706,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 233 /* VariableDeclarationList */) { + if (node.kind === 236 /* VariableDeclarationList */) { emit(node); } else { @@ -78723,7 +80808,7 @@ var ts; emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); } function emitVariableDeclarationList(node) { - writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); writeSpace(); emitList(node, node.declarations, 272 /* VariableDeclarationList */); } @@ -78916,7 +81001,7 @@ var ts; var body = node.body; if (!body) return writeSemicolon(); - while (body.kind === 239 /* ModuleDeclaration */) { + while (body.kind === 242 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); body = body.body; @@ -79717,8 +81802,8 @@ var ts; function writeLines(text) { var lines = text.split(/\r\n?|\n/g); var indentation = ts.guessIndentation(lines); - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var lineText = lines_1[_a]; + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var lineText = lines_2[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); @@ -79841,7 +81926,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 191 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -79906,81 +81991,81 @@ var ts; if (!node) return; switch (node.kind) { - case 213 /* Block */: + case 216 /* Block */: ts.forEach(node.statements, generateNames); break; - case 228 /* LabeledStatement */: - case 226 /* WithStatement */: - case 218 /* DoStatement */: - case 219 /* WhileStatement */: + case 231 /* LabeledStatement */: + case 229 /* WithStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: generateNames(node.statement); break; - case 217 /* IfStatement */: + case 220 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 220 /* ForStatement */: - case 222 /* ForOfStatement */: - case 221 /* ForInStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: + case 224 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 266 /* CaseClause */: - case 267 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 230 /* TryStatement */: + case 233 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 269 /* CatchClause */: + case 272 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: generateNames(node.declarationList); break; - case 233 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: case 149 /* Parameter */: - case 182 /* BindingElement */: - case 235 /* ClassDeclaration */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 180 /* ObjectBindingPattern */: - case 181 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: generateNames(node.importClause); break; - case 245 /* ImportClause */: + case 248 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 246 /* NamespaceImport */: + case 249 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 247 /* NamedImports */: + case 250 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 248 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -79989,8 +82074,8 @@ var ts; if (!node) return; switch (node.kind) { - case 270 /* PropertyAssignment */: - case 271 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: case 152 /* PropertyDeclaration */: case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: @@ -80176,17 +82261,17 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 239 /* ModuleDeclaration */: - case 238 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 244 /* ImportDeclaration */: - case 250 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 234 /* FunctionDeclaration */: - case 235 /* ClassDeclaration */: - case 249 /* ExportAssignment */: + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 252 /* ExportAssignment */: return generateNameForExportDefault(); - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: return generateNameForClassExpression(); case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: @@ -80539,7 +82624,7 @@ var ts; case WatchLogLevel.TriggerOnly: return createFileWatcherWithTriggerLogging; case WatchLogLevel.Verbose: - return createFileWatcherWithLogging; + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; } } function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { @@ -80552,9 +82637,27 @@ var ts; } }; } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { return addWatch(host, file, function (fileName, cbOptional) { - var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); log(triggerredInfo); var start = ts.timestamp(); cb(fileName, cbOptional, passThrough); @@ -80684,7 +82787,7 @@ var ts; } } ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -80779,6 +82882,8 @@ var ts; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; + var halfIndent = " "; + var indent = " "; function getCategoryFormat(category) { switch (category) { case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; @@ -80798,62 +82903,74 @@ var ts; } return s; } + function formatCodeSpan(file, start, length, indent, squiggleColor, host) { + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + var context = ""; + for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + // 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) { + context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + // Output the gutter and the error span for the line using tildes. + context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; + } + /* @internal */ + function formatLocation(file, start, host, color) { + if (color === void 0) { color = formatColorAndReset; } + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var output = ""; + output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + return output; + } + ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; - var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 - var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), 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; - var gutterWidth = (lastLine + 1 + "").length; - if (hasMoreThanFiveLines) { - gutterWidth = Math.max(ellipsis.length, gutterWidth); - } - for (var i = firstLine; i <= lastLine; i++) { - context += host.getNewLine(); - // 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) { - context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); - i = lastLine - 1; - } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); - lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces - // Output the gutter and the actual contents of the line. - context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += lineContent + host.getNewLine(); - // Output the gutter and the error span for the line using tildes. - context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += ForegroundColorEscapeSequences.Red; - if (i === firstLine) { - // If we're on the last line, then limit it to the last character of the last line. - // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. - var lastCharForLine = i === lastLine ? lastLineChar : undefined; - context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); - } - else if (i === lastLine) { - context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); - } - else { - // Squiggle the entire line. - context += lineContent.replace(/./g, "~"); - } - context += resetEscapeSequence; - } - output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); - output += ":"; - output += formatColorAndReset("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); - output += ":"; - output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + var file = diagnostic.file, start = diagnostic.start; + output += formatLocation(file, start, host); // TODO: GH#18217 output += " - "; } output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); @@ -80861,7 +82978,20 @@ var ts; output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); - output += context; + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217 + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { + var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } } output += host.getNewLine(); } @@ -80875,16 +83005,16 @@ var ts; else { var diagnosticChain = messageText; var result = ""; - var indent = 0; + var indent_1 = 0; while (diagnosticChain) { - if (indent) { + if (indent_1) { result += newLine; - for (var i = 0; i < indent; i++) { + for (var i = 0; i < indent_1; i++) { result += " "; } } result += diagnosticChain.messageText; - indent++; + indent_1++; diagnosticChain = diagnosticChain.next; } return result; @@ -81019,6 +83149,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -81056,7 +83187,8 @@ var ts; var packageIdToSourceFile = ts.createMap(); // Maps from a SourceFile's `.path` to the name of the package it was imported with. var sourceFileToPackageName = ts.createMap(); - var redirectTargetsSet = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -81163,7 +83295,7 @@ var ts; getSourceFileFromReference: getSourceFileFromReference, getLibFileFromReference: getLibFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsMap: redirectTargetsMap, isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -81246,13 +83378,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_3 = []; + var result_4 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); + result_4.push(resolvedModule); } - return result_3; + return result_4; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -81449,7 +83581,7 @@ var ts; fileChanged = false; newSourceFile = oldSourceFile; // Use the redirect. } - else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { // If a redirected-to source file changes, the redirect may be broken. if (newSourceFile !== oldSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -81576,13 +83708,23 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; - redirectTargetsSet = oldProgram.redirectTargetsSet; + redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {})); + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + // Use local caches + var path = toPath(f); + if (getSourceFileByPath(path)) + return true; + if (ts.contains(missingFilePaths, path)) + return false; + // Before falling back to the host + return host.fileExists(f); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } function getProjectReferences() { if (!resolvedProjectReferences) @@ -81603,10 +83745,12 @@ var ts; continue; var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMap = host.readFile(resolvedRefOpts.options.outFile + ".map"); // TODO: try to read sourceMappingUrl comment from the js file + var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; - var dtsMap = host.readFile(dtsFilename + ".map"); - var node = ts.createInputFiles(js, dts, jsMap, dtsMap); + var dtsMapPath = dtsFilename + ".map"; + var dtsMap = host.readFile(dtsMapPath); + var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap); nodes.push(node); } } @@ -81758,10 +83902,7 @@ var ts; } function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { - // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a - // '/// ' directive. - if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { + if (ts.skipTypeChecking(sourceFile, options)) { return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); @@ -81840,10 +83981,10 @@ var ts; case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 192 /* FunctionExpression */: - case 234 /* FunctionDeclaration */: - case 193 /* ArrowFunction */: - case 232 /* VariableDeclaration */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: + case 235 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -81851,41 +83992,41 @@ var ts; } } switch (node.kind) { - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return; - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return; } break; - case 268 /* HeritageClause */: + case 271 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 108 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return; } break; - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return; - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return; - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return; - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 209 /* NonNullExpression */: + case 211 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; - case 208 /* AsExpression */: + case 210 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return; - case 190 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; @@ -81898,25 +84039,25 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); } switch (parent.kind) { - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 192 /* FunctionExpression */: - case 234 /* FunctionDeclaration */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; } // falls through - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 214 /* VariableStatement */); + return checkModifiers(nodes, parent.kind === 217 /* VariableStatement */); } break; case 152 /* PropertyDeclaration */: @@ -81938,11 +84079,11 @@ var ts; return; } break; - case 187 /* CallExpression */: - case 188 /* NewExpression */: - case 207 /* ExpressionWithTypeArguments */: - case 256 /* JsxSelfClosingElement */: - case 257 /* JsxOpeningElement */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 209 /* ExpressionWithTypeArguments */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); @@ -81950,8 +84091,8 @@ var ts; } break; } - for (var _b = 0, nodes_5 = nodes; _b < nodes_5.length; _b++) { - var node = nodes_5[_b]; + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; walk(node); } } @@ -82155,7 +84296,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -82233,9 +84374,17 @@ var ts; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path - // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } } // If the file was previously found via a node_modules search, but is now being processed as a root file, // then everything it sucks in may also be marked incorrectly, and needs to be checked again. @@ -82288,7 +84437,7 @@ var ts; // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 - redirectTargetsSet.set(fileFromPackageId.path, true); + redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); @@ -82518,7 +84667,7 @@ var ts; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); allFilesBelongToPath = false; } } @@ -82528,13 +84677,14 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); // TODO: GH#18217 + var refPath = resolveProjectReferencePath(host, ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); if (sourceFile === undefined) { return undefined; } + sourceFile.path = toPath(refPath); var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } @@ -82548,7 +84698,7 @@ var ts; ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 } function verifyCompilerOptions() { - if (options.strictPropertyInitialization && !options.strictNullChecks) { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { @@ -82608,14 +84758,14 @@ var ts; if (options.composite && rootNames.length < files.length) { var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_8 = function (file) { + var _loop_9 = function (file) { if (normalizedRootNames.every(function (r) { return r !== file; })) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); } }; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var file = sourceFiles_4[_i]; - _loop_8(file); + _loop_9(file); } } if (options.paths) { @@ -82672,7 +84822,7 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } - if (options.declarationMap && !options.declaration) { + if (options.declarationMap && !ts.getEmitDeclarations(options)) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); } if (options.lib && options.noLib) { @@ -82713,6 +84863,10 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } + // Any emit other than common js is error + else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + } } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted @@ -82844,12 +84998,12 @@ var ts; } function createDiagnosticForReference(index, message, arg0, arg1) { var referencesSyntax = getProjectReferencesSyntax(); - if (referencesSyntax) { - if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { - return; - } + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); @@ -82899,14 +85053,6 @@ var ts; } return !!props.length; } - function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { - if (arrayLiteral.elements.length <= index) { - // Out-of-bounds - return false; - } - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); - return false; // TODO: GH#18217 This function always returns `false`!` - } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -82959,7 +85105,8 @@ var ts; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; /** - * Returns the target config filename of a project reference + * Returns the target config filename of a project reference. + * Note: The file might not exist. */ function resolveProjectReferencePath(host, ref) { if (!host.fileExists(ref.path)) { @@ -82979,7 +85126,6 @@ var ts; switch (extension) { case ".ts" /* Ts */: case ".d.ts" /* Dts */: - case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check // These are always allowed. return undefined; case ".tsx" /* Tsx */: @@ -82988,6 +85134,8 @@ var ts; return needJsx() || needAllowJs(); case ".js" /* Js */: return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); } function needJsx() { return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; @@ -82995,6 +85143,9 @@ var ts; function needAllowJs() { return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } } ts.getResolutionDiagnostic = getResolutionDiagnostic; function getModuleNames(_a) { @@ -83016,7 +85167,7 @@ var ts; function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -83027,6 +85178,22 @@ var ts; (function (ts) { var BuilderState; (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.path; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -83039,12 +85206,9 @@ var ts; var checker = program.getTypeChecker(); for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); } } } @@ -83089,6 +85253,7 @@ var ts; function create(newProgram, getCanonicalFileName, oldState) { var fileInfos = ts.createMap(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; var hasCalledUpdateShapeSignature = ts.createMap(); var useOldState = canReuseOldState(referencedMap, oldState); // Create the reference map, and set the file infos @@ -83101,12 +85266,20 @@ var ts; if (newReferences) { referencedMap.set(sourceFile.path, newReferences); } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } } fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); } return { fileInfos: fileInfos, referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, allFilesExcludingDefaultLibraryFile: undefined, allFileNames: undefined @@ -83116,7 +85289,7 @@ var ts; /** * Gets the files affected by the path from the program */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { // Since the operation could be cancelled, the signatures are always stored in the cache // They will be commited once it is safe to use them // eg when calling this api from tsserver, if there is no cancellation of the operation @@ -83126,10 +85299,10 @@ var ts; if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); if (!cacheToUpdateSignature) { // Commit all the signatures in the signature cache updateSignaturesFromCache(state, signatureCache); @@ -83151,8 +85324,9 @@ var ts; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { return false; @@ -83169,6 +85343,9 @@ var ts; var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } } else { latestSignature = prevSignature; // TODO: GH#18217 @@ -83177,6 +85354,44 @@ var ts; cacheToUpdateSignature.set(sourceFile.path, latestSignature); return !prevSignature || latestSignature !== prevSignature; } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -83286,7 +85501,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -83306,7 +85521,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 queue, getReferencedByPaths(state, currentPath)); } @@ -83337,7 +85552,8 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -83373,6 +85589,10 @@ var ts; var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); } } }); @@ -83394,14 +85614,14 @@ var ts; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { - var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var seenAffectedFiles = state.seenAffectedFiles; var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 while (affectedFilesIndex < affectedFiles.length) { var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.path)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - semanticDiagnosticsPerFile.delete(affectedFile.path); + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); return affectedFile; } seenAffectedFiles.set(affectedFile.path, true); @@ -83413,6 +85633,7 @@ var ts; // Commit the changes in file signature ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); state.affectedFiles = undefined; } // Get next changed file @@ -83430,13 +85651,66 @@ var ts; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; - state.semanticDiagnosticsPerFile.delete(nextKey.value); state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return false; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } /** * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly @@ -83703,6 +85977,7 @@ var ts; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -83760,6 +86035,7 @@ var ts; function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); @@ -83799,17 +86075,19 @@ var ts; perDirectoryResolvedModuleNames.clear(); nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); - clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); @@ -83861,7 +86139,7 @@ var ts; perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); - watchFailedLookupLocationOfResolution(resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } @@ -83957,20 +86235,31 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, "/node_modules/")) { + while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } - // If the directory is node_modules use it to watch + // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } + var nonRecursive = true; // Use some ancestor of the root directory var subDirectoryPath, subDirectory; if (rootPath !== undefined) { @@ -83979,33 +86268,43 @@ var ts; if (parentPath === dirPath) { break; } + nonRecursive = false; subDirectoryPath = dirPath; subDirectory = dir; dirPath = parentPath; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath }, dirPath); + return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); } - function watchFailedLookupLocationOfResolution(resolution) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { // No need to set the resolution refCount - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { - return; - } - if (resolution.refCount !== undefined) { - resolution.refCount++; - return; + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } } - resolution.refCount = 1; + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); var failedLookupLocations = resolution.failedLookupLocations; var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore; if (!ignore) { // If the failed lookup location path is not one of the supported extensions, // store it in the custom path @@ -84014,28 +86313,40 @@ var ts; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); } if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); setAtRoot = true; } else { - setDirectoryWatcher(dir, dirPath); + setDirectoryWatcher(dir, dirPath, nonRecursive); } } } if (setAtRoot) { - setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } } - function setDirectoryWatcher(dir, dirPath) { + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } + function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { + ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); dirWatcher.refCount++; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); } } function stopWatchFailedLookupLocationOfResolution(resolution) { - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + if (!resolution.refCount) { return; } resolution.refCount--; @@ -84076,7 +86387,7 @@ var ts; // Do not close the watcher yet since it might be needed by other failed lookup locations. dirWatcher.refCount--; } - function createDirectoryWatcher(directory, dirPath) { + function createDirectoryWatcher(directory, dirPath, nonRecursive) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { @@ -84086,7 +86397,7 @@ var ts; if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { resolutionHost.onInvalidatedResolution(); } - }, 1 /* Recursive */); + }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); } function removeResolutionsOfFileFromCache(cache, filePath) { // Deleted file, stop watching failed lookups for all the resolutions in the file @@ -84258,28 +86569,45 @@ var ts; } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); -// Used by importFixes to synthesize import module specifiers. +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { - // Note: fromSourceFile is just for usesJsExtensionOnImports - function getModuleSpecifier(compilerOptions, fromSourceFile, fromSourceFileName, toFileName, host, preferences) { + // Note: importingSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, fromSourceFile, fromSourceFileName, host); - return getGlobalModuleSpecifier(toFileName, info, host, compilerOptions) || + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { + var isBundle = (compilerOptions.out || compilerOptions.outFile); + if (isBundle && host.getCommonSourceDirectory) { + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); + } + var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; + return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + } + moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) return [[ambient]]; - var compilerOptions = program.getCompilerOptions(); - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.fileName, host); - var modulePaths = getAllModulePaths(program, ts.getSourceFileOfNode(moduleSymbol.valueDeclaration)); + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); + if (!files) { + return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); + } + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); @@ -84297,13 +86625,13 @@ var ts; function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || compilerOptions.rootDirs && tryGetModuleNameFromRootDirs(compilerOptions.rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); } function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; - var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { return [relativePath]; } @@ -84364,18 +86692,66 @@ var ts; return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; }) || false; } - /** - * Looks for a existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); + var symlinks = ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; }); }); - return symlinks.length === 0 ? [fileName] : symlinks; + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); + } + return result; + } + /** + * Looks for existing imports that use symlinks to this module. + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } + }); + result.push.apply(result, targets); + return result; } function getRelativePathNParents(relativePath) { var components = ts.getPathComponents(relativePath); @@ -84388,8 +86764,8 @@ var ts; return components.length - 1; } function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { return decl.name.text; } } @@ -84399,10 +86775,7 @@ var ts; var patternText_1 = _a[_i]; var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { + if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && @@ -84451,7 +86824,7 @@ var ts; var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex))) + if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); @@ -84484,8 +86857,8 @@ var ts; function tryGetAnyFileFromPath(host, path) { // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var e = extensions_1[_i]; + for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { + var e = extensions_3[_i]; var fullPath = path + e; if (host.fileExists(fullPath)) { // TODO: GH#18217 return fullPath; @@ -84515,7 +86888,7 @@ var ts; partEnd = fullPath.indexOf("/", partStart + 1); switch (state) { case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { topLevelNodeModulesIndex = partStart; topLevelPackageNameIndex = partEnd; state = 1 /* NodeModules */; @@ -84532,7 +86905,7 @@ var ts; } break; case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { state = 1 /* NodeModules */; } else { @@ -84717,6 +87090,7 @@ var ts; createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; } var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); @@ -84845,21 +87219,20 @@ var ts; }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); - if (configFileName) { + if (configFileName && !host.configFileParsingResult) { newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); - if (host.configFileParsingResult) { - setConfigFileParsingResult(host.configFileParsingResult); - } - else { - ts.Debug.assert(!rootFileNames); - parseConfigFile(); - } + ts.Debug.assert(!rootFileNames); + parseConfigFile(); newLine = updateNewLine(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : - compilerOptions.diagnostis ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); @@ -85383,7 +87756,6 @@ var ts; getKeys: getKeys }; } - ts.createDependencyMapper = createDependencyMapper; function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); @@ -85392,16 +87764,20 @@ var ts; function getOutputJavaScriptFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); - return ts.changeExtension(outputPath, (ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */) ? ".jsx" /* Jsx */ : ".js" /* Js */); + var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : + ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + return ts.changeExtension(outputPath, newExtension); } function getOutputFileNames(inputFileName, configFile) { - if (configFile.options.outFile) { + // outFile is handled elsewhere; .d.ts files don't generate outputs + if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) { return ts.emptyArray; } var outputs = []; outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); - if (configFile.options.declaration) { - var dts = outputs.push(getOutputDeclarationFileName(inputFileName, configFile)); + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + var dts = getOutputDeclarationFileName(inputFileName, configFile); + outputs.push(dts); if (configFile.options.declarationMap) { outputs.push(dts + ".map"); } @@ -85414,7 +87790,7 @@ var ts; } var outputs = []; outputs.push(project.options.outFile); - if (project.options.declaration) { + if (ts.getEmitDeclarations(project.options)) { var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { @@ -85509,8 +87885,8 @@ var ts; var clean = false; var watch = false; var projects = []; - for (var _i = 0, args_3 = args; _i < args_3.length; _i++) { - var arg = args_3[_i]; + for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { + var arg = args_6[_i]; switch (arg.toLowerCase()) { case "-v": case "--verbose": @@ -85534,23 +87910,28 @@ var ts; case "--?": case "-?": case "--help": - return ts.printHelp(buildOpts, "--build "); + ts.printHelp(buildOpts, "--build "); + return ts.ExitStatus.Success; } // Not a flag, parse as filename addProject(arg); } // Nonsensical combinations if (clean && force) { - return buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } if (clean && verbose) { - return buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } if (clean && watch) { - return buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } if (watch && dry) { - return buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." @@ -85558,20 +87939,17 @@ var ts; } var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); if (clean) { - builder.cleanAllProjects(); - } - else { - builder.buildAllProjects(); + return builder.cleanAllProjects(); } if (watch) { - return builder.startWatching(); + builder.buildAllProjects(); + builder.startWatching(); + return undefined; } + return builder.buildAllProjects(); function addProject(projectSpecification) { var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!refPath) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, projectSpecification); - } if (!compilerHost.fileExists(refPath)) { return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); } @@ -85590,6 +87968,14 @@ var ts; var configFileCache = createConfigFileCache(compilerHost); var context = createBuildContext(defaultOptions); var existingWatchersForWildcards = ts.createMap(); + var upToDateHost = { + fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, + getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, + getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, + getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, + setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, + parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } + }; return { buildAllProjects: buildAllProjects, getUpToDateStatus: getUpToDateStatus, @@ -85613,7 +87999,7 @@ var ts; // Everything is broken - we don't even know what to watch. Give up. return; } - var _loop_9 = function (resolved) { + var _loop_10 = function (resolved) { var cfg = configFileCache.parseConfigFile(resolved); if (cfg) { // Watch this file @@ -85640,7 +88026,7 @@ var ts; }; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var resolved = _a[_i]; - _loop_9(resolved); + _loop_10(resolved); } function invalidateProjectAndScheduleBuilds(resolved) { invalidateProject(resolved); @@ -85665,16 +88051,7 @@ var ts; return getBuildGraph(rootNames); } function getUpToDateStatus(project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; - } - var prior = context.projectStatus.getValueOrUndefined(project.options.configFilePath); - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(project); - context.projectStatus.setValue(project.options.configFilePath, actual); - return actual; + return ts.getUpToDateStatus(upToDateHost, project); } function invalidateProject(configFileName) { var resolved = resolveProjectName(configFileName); @@ -85694,7 +88071,6 @@ var ts; } // Mark all downstream projects of this one needing to be built "later" function queueBuildForDownstreamReferences(root) { - debugger; var deps = graph.dependencyMap.getReferencesTo(root); for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { var ref = deps_1[_i]; @@ -85737,153 +88113,6 @@ var ts; buildSingleProject(next); } } - function getAllProjectOutputs(project) { - if (project.options.outFile) { - return getOutFileOutputs(project); - } - else { - var outputs = []; - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); - } - return outputs; - } - } - function getUpToDateStatusWorker(project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!compilerHost.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = compilerHost.getModifiedTime(inputFile); - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!compilerHost.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = compilerHost.getModifiedTime(output); - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = context.unchangedOutputs.getValueOrUndefined(output); - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, compilerHost.getModifiedTime(output)); - } - } - } - var pseudoUpToDate = false; - if (project.projectReferences) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - var resolvedRef = ts.resolveProjectReferencePath(compilerHost, ref); - var refStatus = getUpToDateStatus(configFileCache.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; - } function createDependencyGraph(roots) { var temporaryMarks = {}; var permanentMarks = {}; @@ -85967,7 +88196,7 @@ var ts; }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { resultFlags |= BuildResultFlags.SyntaxErrors; for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { @@ -85978,7 +88207,7 @@ var ts; return resultFlags; } // Don't emit .d.ts if there are decl file errors - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { resultFlags |= BuildResultFlags.DeclarationEmitErrors; @@ -86002,14 +88231,18 @@ var ts; return resultFlags; } var newestDeclarationFileContentChangedTime = minimumDate; + var anyDtsChanged = false; program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { + if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { if (compilerHost.readFile(fileName) === content) { // Check for unchanged .d.ts files resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); } + else { + anyDtsChanged = true; + } } compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { @@ -86017,22 +88250,27 @@ var ts; context.unchangedOutputs.setValue(fileName, priorChangeTime); } }); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime }); + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + }; + context.projectStatus.setValue(proj, status); return resultFlags; } function updateOutputTimestamps(proj) { if (context.options.dry) { return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) + if (context.options.verbose) { buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { - var file = outputs_2[_i]; + for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { + var file = outputs_1[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file)); + priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); } compilerHost.setModifiedTime(file, now); } @@ -86055,8 +88293,8 @@ var ts; continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; + for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { + var output = outputs_2[_b]; if (compilerHost.fileExists(output)) { filesToDelete.push(output); } @@ -86076,14 +88314,17 @@ var ts; function cleanAllProjects() { var resolvedNames = getAllProjectsInScope(); if (resolvedNames === undefined) { - return buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); + buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } var filesToDelete = getFilesToClean(resolvedNames); if (filesToDelete === undefined) { - return buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); + buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + return ts.ExitStatus.Success; } // Do this check later to allow --clean --dry to function even if the host can't delete files if (!compilerHost.deleteFile) { @@ -86093,6 +88334,7 @@ var ts; var output = filesToDelete_1[_i]; compilerHost.deleteFile(output); } + return ts.ExitStatus.Success; } function resolveProjectName(name) { var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); @@ -86121,13 +88363,15 @@ var ts; function buildAllProjects() { var graph = getGlobalDependencyGraph(); if (graph === undefined) - return; + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; var queue = graph.buildQueue; reportBuildQueue(graph); + var anyFailed = false; for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { var next = queue_1[_i]; var proj = configFileCache.parseConfigFile(next); if (proj === undefined) { + anyFailed = true; break; } var status = getUpToDateStatus(proj); @@ -86155,8 +88399,10 @@ var ts; // Do nothing continue; } - buildSingleProject(next); + var buildResult = buildSingleProject(next); + anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } /** * Report the build ordering inferred from the current project graph if we're in verbose mode @@ -86175,63 +88421,640 @@ var ts; function relName(path) { return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); } + function reportVerbose(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + buildHost.verbose.apply(buildHost, [message].concat(args)); + } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { if (!context.options.verbose) return; - switch (status.type) { - case UpToDateStatusType.OutOfDateWithSelf: - return buildHost.verbose(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); - case UpToDateStatusType.OutOfDateWithUpstream: - return buildHost.verbose(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); - case UpToDateStatusType.OutputMissing: - return buildHost.verbose(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); - case UpToDateStatusType.UpToDate: - if (status.newestInputFileTime !== undefined) { - return buildHost.verbose(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName), relName(status.oldestOutputFileName)); - } - // Don't report anything for "up to date because it was already built" -- too verbose - break; - case UpToDateStatusType.UpToDateWithUpstreamTypes: - return buildHost.verbose(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); - case UpToDateStatusType.UpstreamOutOfDate: - return buildHost.verbose(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); - case UpToDateStatusType.UpstreamBlocked: - return buildHost.verbose(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); - case UpToDateStatusType.Unbuildable: - return buildHost.verbose(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); - case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects - break; - default: - ts.assertTypeIsNever(status); - } + return formatUpToDateStatus(configFileName, status, relName, reportVerbose); } } ts.createSolutionBuilder = createSolutionBuilder; + /** + * Gets the UpToDateStatus for a project + */ + function getUpToDateStatus(host, project) { + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(host, project); + if (host.setLastStatus) { + host.setLastStatus(project.options.configFilePath, actual); + } + return actual; + } + ts.getUpToDateStatus = getUpToDateStatus; + function getUpToDateStatusWorker(host, project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } + } + } + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences && host.parseConfigFile) { + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(host, ref); + var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function getAllProjectOutputs(project) { + if (project.options.outFile) { + return getOutFileOutputs(project); + } + else { + var outputs = []; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); + } + return outputs; + } + } + ts.getAllProjectOutputs = getAllProjectOutputs; + function formatUpToDateStatus(configFileName, status, relName, formatMessage) { + switch (status.type) { + case UpToDateStatusType.OutOfDateWithSelf: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); + case UpToDateStatusType.OutOfDateWithUpstream: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); + case UpToDateStatusType.OutputMissing: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); + case UpToDateStatusType.UpToDate: + if (status.newestInputFileTime !== undefined) { + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || "")); + } + // Don't report anything for "up to date because it was already built" -- too verbose + break; + case UpToDateStatusType.UpToDateWithUpstreamTypes: + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); + case UpToDateStatusType.UpstreamOutOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.UpstreamBlocked: + return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.Unbuildable: + return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.ContainerOnly: + // Don't report status on "solution" projects + break; + default: + ts.assertType(status); + } + } + ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); -//# sourceMappingURL=compiler.js.map -"use strict"; -var __assign = (this && this.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; +/* @internal */ +var ts; +(function (ts) { + var server; + (function (server) { + // tslint:disable variable-name + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + server.EventInitializationFailed = "event::initializationFailed"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ + Arguments.NpmLocation = "--npmLocation"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + /*@internal*/ + function nowString() { + // E.g. "12:34:56.789" + var d = new Date(); + return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); + } + server.nowString = nowString; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + /* @internal */ + function isTypingUpToDate(cachedTyping, availableTypingVersions) { + var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return !availableVersion.greaterThan(cachedTyping.version); + } + JsTyping.isTypingUpToDate = isTypingUpToDate; + /* @internal */ + JsTyping.nodeCoreModuleList = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" + ]; + /* @internal */ + JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; + function loadTypesMap(host, typesMapPath) { + var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); + if (result.config) { + return ts.createMapFromTemplate(result.config.simpleMap); + } + return undefined; + } + JsTyping.loadTypesMap = loadTypesMap; + /** + * @param host is the object providing I/O related operations. + * @param fileNames are the file names that belong to the same project + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions + * @param typeAcquisition is used to customize the typing acquisition process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + // Only infer typings for .js and .jsx files + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJavaScriptFileExtension(path)) { + return path; + } + }); + var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + // Directories to search for package.json, bower.json and other typing information + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); + getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); + } + // Add the cached typing locations for inferred typings that are already installed + packageNameToTypingLocation.forEach(function (typing, name) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { + inferredTypings.set(name, typing.typingLocation); + } + }); + // Remove typings that the user has added to the exclude list + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); + } + var newTypingNames = []; + var cachedTypingPaths = []; + inferredTypings.forEach(function (inferred, typing) { + if (inferred !== undefined) { + cachedTypingPaths.push(inferred); + } + else { + newTypingNames.push(typing); + } + }); + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); // TODO: GH#18217 + } + } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (!host.fileExists(jsonPath)) { + return; + } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJavaScriptFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); + } + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); + if (hasJsxFile) { + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); + } + } + /** + * Infer typing names from packages folder (ex: node_module, bower_components) + * @param packagesFolderPath is the path to the packages folder + */ + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { + filesToWatch.push(packagesFolderPath); + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(packagesFolderPath)) { + return; + } + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var normalizedFileName = ts.normalizePath(fileName); + var baseFileName = ts.getBaseFileName(normalizedFileName); + if (baseFileName !== "package.json" && baseFileName !== "bower.json") { + continue; + } + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (baseFileName === "package.json" && packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); + inferredTypings.set(packageJson.name, absolutePath); + } + else { + packageNames.push(packageJson.name); + } + } + addInferredTypings(packageNames, " Found package names"); + } + } + JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + return ts.Debug.fail(); // Shouldn't have called this. + default: + throw ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function stringToInt(str) { + var n = parseInt(str, 10); + if (isNaN(n)) { + throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); + } + return n; } - return t; -}; -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); + var isPrereleaseRegex = /^(.*)-next.\d+/; + var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; + var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; + var Semver = /** @class */ (function () { + function Semver(major, minor, patch, + /** + * If true, this is `major.minor.0-next.patch`. + * If false, this is `major.minor.patch`. + */ + isPrerelease) { + this.major = major; + this.minor = minor; + this.patch = patch; + this.isPrerelease = isPrerelease; + } + Semver.parse = function (semver) { + var isPrerelease = isPrereleaseRegex.test(semver); + var result = Semver.tryParse(semver, isPrerelease); + if (!result) { + throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); + } + return result; + }; + Semver.fromRaw = function (_a) { + var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; + return new Semver(major, minor, patch, isPrerelease); + }; + // This must parse the output of `versionString`. + Semver.tryParse = function (semver, isPrerelease) { + // Per the semver spec : + // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." + var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; + var match = rgx.exec(semver); + return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; + }; + Object.defineProperty(Semver.prototype, "versionString", { + get: function () { + return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; + }, + enumerable: true, + configurable: true + }); + Semver.prototype.equals = function (sem) { + return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; + }; + Semver.prototype.greaterThan = function (sem) { + return this.major > sem.major || this.major === sem.major + && (this.minor > sem.minor || this.minor === sem.minor + && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease + && this.patch > sem.patch)); + }; + return Semver; + }()); + ts.Semver = Semver; +})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -86261,7 +89084,7 @@ var ts; ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); /* @internal */ - ts.defaultPreferences = {}; + ts.emptyOptions = {}; var TextChange = /** @class */ (function () { function TextChange() { } @@ -86497,35 +89320,35 @@ var ts; function getMeaningFromDeclaration(node) { switch (node.kind) { case 149 /* Parameter */: - case 232 /* VariableDeclaration */: - case 182 /* BindingElement */: + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: - case 270 /* PropertyAssignment */: - case 271 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: - case 269 /* CatchClause */: - case 262 /* JsxAttribute */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 272 /* CatchClause */: + case 265 /* JsxAttribute */: return 1 /* Value */; case 148 /* TypeParameter */: - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: case 166 /* TypeLiteral */: return 2 /* Type */; - case 297 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 273 /* EnumMember */: - case 235 /* ClassDeclaration */: + case 276 /* EnumMember */: + case 238 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -86535,26 +89358,26 @@ var ts; else { return 4 /* Namespace */; } - case 238 /* EnumDeclaration */: - case 247 /* NamedImports */: - case 248 /* ImportSpecifier */: - case 243 /* ImportEqualsDeclaration */: - case 244 /* ImportDeclaration */: - case 249 /* ExportAssignment */: - case 250 /* ExportDeclaration */: + case 241 /* EnumDeclaration */: + case 250 /* NamedImports */: + case 251 /* ImportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 252 /* ExportAssignment */: + case 253 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 274 /* SourceFile */: + case 277 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 274 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 249 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -86587,7 +89410,7 @@ var ts; // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace var name = node.kind === 146 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 243 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + return name && name.parent.kind === 246 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 146 /* QualifiedName */) { @@ -86613,16 +89436,16 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 185 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 185 /* PropertyAccessExpression */) { + if (root.parent.kind === 187 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 187 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 207 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 268 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 209 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 271 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 235 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || - (decl.kind === 236 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); + return (decl.kind === 238 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || + (decl.kind === 239 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); } return false; } @@ -86633,30 +89456,34 @@ var ts; switch (node.kind) { case 99 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 174 /* ThisType */: + case 176 /* ThisType */: return true; } switch (node.parent.kind) { case 162 /* TypeReference */: return true; - case 179 /* ImportType */: + case 181 /* ImportType */: return !node.parent.isTypeOf; - case 207 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 187 /* CallExpression */); + return isCallOrNewExpressionTargetWorker(node, ts.isCallExpression); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 188 /* NewExpression */); + return isCallOrNewExpressionTargetWorker(node, ts.isNewExpression); } ts.isNewExpressionTarget = isNewExpressionTarget; - function isCallOrNewExpressionTarget(node, kind) { + function isCallOrNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallOrNewExpression); + } + ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget; + function isCallOrNewExpressionTargetWorker(node, pred) { var target = climbPastPropertyAccess(node); - return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && pred(target.parent) && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -86664,7 +89491,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 228 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 231 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -86689,11 +89516,11 @@ var ts; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 185 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 239 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 242 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { @@ -86705,20 +89532,20 @@ var ts; switch (node.parent.kind) { case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: - case 270 /* PropertyAssignment */: - case 273 /* EnumMember */: + case 273 /* PropertyAssignment */: + case 276 /* EnumMember */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return node.parent.argumentExpression === node; case 147 /* ComputedPropertyName */: return true; - case 178 /* LiteralType */: - return node.parent.parent.kind === 176 /* IndexedAccessType */; + case 180 /* LiteralType */: + return node.parent.parent.kind === 178 /* IndexedAccessType */; default: return false; } @@ -86742,17 +89569,17 @@ var ts; return undefined; } switch (node.kind) { - case 274 /* SourceFile */: + case 277 /* SourceFile */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 238 /* EnumDeclaration */: - case 239 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: return node; } } @@ -86760,26 +89587,26 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 274 /* SourceFile */: + case 277 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return "class" /* classElement */; - case 236 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 237 /* TypeAliasDeclaration */: - case 292 /* JSDocCallbackTag */: - case 297 /* JSDocTypedefTag */: + case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 240 /* TypeAliasDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 238 /* EnumDeclaration */: return "enum" /* enumElement */; - case 232 /* VariableDeclaration */: + case 241 /* EnumDeclaration */: return "enum" /* enumElement */; + case 235 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 182 /* BindingElement */: + case 184 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 193 /* ArrowFunction */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return "function" /* functionElement */; case 156 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; case 157 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; @@ -86794,15 +89621,14 @@ var ts; case 158 /* CallSignature */: return "call" /* callSignatureElement */; case 155 /* Constructor */: return "constructor" /* constructorImplementationElement */; case 148 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 273 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 276 /* EnumMember */: return "enum member" /* enumMemberElement */; case 149 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 243 /* ImportEqualsDeclaration */: - case 248 /* ImportSpecifier */: - case 245 /* ImportClause */: - case 252 /* ExportSpecifier */: - case 246 /* NamespaceImport */: + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: + case 249 /* NamespaceImport */: return "alias" /* alias */; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; switch (kind) { @@ -86822,15 +89648,17 @@ var ts; case 6 /* Prototype */: return "local class" /* localClassElement */; default: { - ts.assertTypeIsNever(kind); + ts.assertType(kind); return "" /* unknown */; } } + case 71 /* Identifier */: + return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; } function getKindOfVariableDeclaration(v) { - return ts.isConst(v) + return ts.isVarConst(v) ? "const" /* constElement */ : ts.isLet(v) ? "let" /* letElement */ @@ -86863,6 +89691,10 @@ var ts; return startEndContainsRange(r1.pos, r1.end, r2); } ts.rangeContainsRange = rangeContainsRange; + function rangeContainsRangeExclusive(r1, r2) { + return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end); + } + ts.rangeContainsRangeExclusive = rangeContainsRangeExclusive; function rangeContainsPosition(r, pos) { return r.pos <= pos && pos <= r.end; } @@ -86883,6 +89715,10 @@ var ts; return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); } ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function nodeOverlapsWithStartEnd(node, sourceFile, start, end) { + return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end); + } + ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd; function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { var start = Math.max(start1, start2); var end = Math.min(end1, end2); @@ -86902,28 +89738,28 @@ var ts; return false; } switch (n.kind) { - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 238 /* EnumDeclaration */: - case 184 /* ObjectLiteralExpression */: - case 180 /* ObjectBindingPattern */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 186 /* ObjectLiteralExpression */: + case 182 /* ObjectBindingPattern */: case 166 /* TypeLiteral */: - case 213 /* Block */: - case 240 /* ModuleBlock */: - case 241 /* CaseBlock */: - case 247 /* NamedImports */: - case 251 /* NamedExports */: + case 216 /* Block */: + case 243 /* ModuleBlock */: + case 244 /* CaseBlock */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 188 /* NewExpression */: + case 190 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 187 /* CallExpression */: - case 191 /* ParenthesizedExpression */: - case 173 /* ParenthesizedType */: + case 189 /* CallExpression */: + case 193 /* ParenthesizedExpression */: + case 175 /* ParenthesizedType */: return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); case 163 /* FunctionType */: case 164 /* ConstructorType */: @@ -86931,13 +89767,13 @@ var ts; case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 159 /* ConstructSignature */: case 158 /* CallSignature */: - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -86947,19 +89783,19 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 217 /* IfStatement */: + case 220 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); - case 183 /* ArrayLiteralExpression */: - case 181 /* ArrayBindingPattern */: - case 186 /* ElementAccessExpression */: + case 185 /* ArrayLiteralExpression */: + case 183 /* ArrayBindingPattern */: + case 188 /* ElementAccessExpression */: case 147 /* ComputedPropertyName */: case 168 /* TupleType */: return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); @@ -86968,44 +89804,44 @@ var ts; return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - case 266 /* CaseClause */: - case 267 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 219 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 222 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 218 /* DoStatement */: + case 221 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); case 165 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 195 /* TypeOfExpression */: - case 194 /* DeleteExpression */: - case 196 /* VoidExpression */: - case 203 /* YieldExpression */: - case 204 /* SpreadElement */: + case 197 /* TypeOfExpression */: + case 196 /* DeleteExpression */: + case 198 /* VoidExpression */: + case 205 /* YieldExpression */: + case 206 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 189 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 202 /* TemplateExpression */: + case 204 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 211 /* TemplateSpan */: + case 214 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 250 /* ExportDeclaration */: - case 244 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 201 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -87069,38 +89905,30 @@ var ts; * position >= start and (position < end or (position === end && token is literal or keyword or identifier)) */ function getTouchingPropertyName(sourceFile, position) { - return getTouchingToken(sourceFile, position, /*includeJsDocComment*/ true, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind); }); + return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; /** * Returns the token if position is in [start, end). * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true */ - function getTouchingToken(sourceFile, position, includeJsDocComment, includePrecedingTokenAtEndPosition) { - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false, includeJsDocComment); + function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false); } ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ - function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { - if (includeEndPosition === void 0) { includeEndPosition = false; } - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, includeEndPosition, includeJsDocComment); + function getTokenAtPosition(sourceFile, position) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false); } ts.getTokenAtPosition = getTokenAtPosition; /** Get the token whose text contains the position */ - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition, includeJsDocComment) { + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { var current = sourceFile; outer: while (true) { - if (ts.isToken(current)) { - // exit early - return current; - } // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { var child = _a[_i]; - if (!includeJsDocComment && ts.isJSDocNode(child)) { - continue; - } - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { // If this child begins after position, then all subsequent children will as well. break; @@ -87131,7 +89959,7 @@ var ts; function findTokenOnLeftOfPosition(file, position) { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. - var tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); + var tokenAtPosition = getTokenAtPosition(file, position); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -87145,19 +89973,14 @@ var ts; // this is token that starts at the end of previous token - return it return n; } - var children = n.getChildren(); - for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { - var child = children_1[_i]; + return ts.firstDefined(n.getChildren(), function (child) { var shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || // previous token ends exactly at the beginning of child (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) { - return find(child); - } - } - return undefined; + return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined; + }); } } ts.findNextToken = findNextToken; @@ -87165,7 +89988,7 @@ var ts; * Finds the rightmost token satisfying `token.end <= position`, * excluding `JsxText` tokens containing only whitespace. */ - function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { + function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) { var result = find(startNode || sourceFile); ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; @@ -87182,7 +90005,7 @@ var ts; // we need to find the last token in a previous child. // 2) `position` is within the same span: we recurse on `child`. if (position < child.end) { - var start = child.getStart(sourceFile, includeJsDoc); + var start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc); var lookInPreviousChild = (start >= position) || // cursor in the leading trivia !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child); @@ -87197,7 +90020,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 274 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. @@ -87257,7 +90080,7 @@ var ts; * returns true if the position is in between the open and close elements of an JSX expression. */ function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var token = getTokenAtPosition(sourceFile, position); if (!token) { return false; } @@ -87269,17 +90092,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 265 /* JsxExpression */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 268 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 265 /* JsxExpression */) { + if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 268 /* JsxExpression */) { return true; } //
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 258 /* JsxClosingElement */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 261 /* JsxClosingElement */) { return true; } return false; @@ -87289,7 +90112,7 @@ var ts; return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; } function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var token = getTokenAtPosition(sourceFile, position); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; @@ -87314,7 +90137,21 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(tokenIn, sourceFile) { + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { var token = tokenIn; // This function determines if the node could be type argument position // Since during editing, when type argument list is not complete, @@ -87331,7 +90168,7 @@ var ts; if (!token || !ts.isIdentifier(token)) return undefined; if (!remainingLessThanTokens) { - return { called: token, nTypeArguments: nTypeArguments }; + return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments }; } remainingLessThanTokens--; break; @@ -87394,26 +90231,20 @@ var ts; } return undefined; } - ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; /** * Returns true if the cursor at position in sourceFile is within a comment. * * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) * @param predicate Additional predicate to test on the comment range. */ - function isInComment(sourceFile, position, tokenAtPosition, predicate) { - return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ false, /*precedingToken*/ undefined, tokenAtPosition, predicate); + function isInComment(sourceFile, position, tokenAtPosition) { + return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition); } ts.isInComment = isInComment; function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); - // First, we have to see if this position actually landed in a comment. - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return ts.forEach(commentRanges, jsDocPrefix); - function jsDocPrefix(c) { - var text = sourceFile.text; - return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; - } + var token = getTokenAtPosition(sourceFile, position); + return !!ts.findAncestor(token, ts.isJSDoc); } ts.hasDocComment = hasDocComment; function nodeHasTokens(n, sourceFile) { @@ -87422,7 +90253,7 @@ var ts; return n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { - var flags = ts.getCombinedModifierFlags(node); + var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; var result = []; if (flags & 8 /* Private */) result.push("private" /* privateMemberModifier */); @@ -87442,10 +90273,10 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 162 /* TypeReference */ || node.kind === 187 /* CallExpression */) { + if (node.kind === 162 /* TypeReference */ || node.kind === 189 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 235 /* ClassDeclaration */ || node.kind === 236 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 238 /* ClassDeclaration */ || node.kind === 239 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -87490,18 +90321,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 183 /* ArrayLiteralExpression */ || - node.kind === 184 /* ObjectLiteralExpression */) { + if (node.kind === 185 /* ArrayLiteralExpression */ || + node.kind === 186 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 200 /* BinaryExpression */ && + if (node.parent.kind === 202 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 222 /* ForOfStatement */ && + if (node.parent.kind === 225 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -87509,7 +90340,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 270 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 273 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -87517,23 +90348,25 @@ var ts; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; function isInReferenceComment(sourceFile, position) { - return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return tripleSlashDirectivePrefixRegex.test(commentText); - }); + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - }); + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false); } ts.isInNonReferenceComment = isInNonReferenceComment; + function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) { + var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); + return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); + } function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { return ts.createTextSpanFromBounds(range.pos, range.end); } @@ -87553,6 +90386,7 @@ var ts; ts.typeKeywords = [ 119 /* AnyKeyword */, 122 /* BooleanKeyword */, + 86 /* FalseKeyword */, 128 /* KeyOfKeyword */, 131 /* NeverKeyword */, 95 /* NullKeyword */, @@ -87560,6 +90394,7 @@ var ts; 135 /* ObjectKeyword */, 137 /* StringKeyword */, 138 /* SymbolKeyword */, + 101 /* TrueKeyword */, 105 /* VoidKeyword */, 140 /* UndefinedKeyword */, 141 /* UniqueKeyword */, @@ -87571,8 +90406,7 @@ var ts; ts.isTypeKeyword = isTypeKeyword; /** True if the symbol is for an external module, as opposed to a namespace. */ function isExternalModuleSymbol(moduleSymbol) { - ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); - return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; function nodeSeenTracker() { @@ -87596,13 +90430,13 @@ var ts; } ts.repeatString = repeatString; function skipConstraint(type) { - return type.isTypeParameter() ? type.getConstraint() : type; // TODO: GH#18217 + return type.isTypeParameter() ? type.getConstraint() || type : type; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { return name.kind === 147 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal - ? ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined + ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.getTextOfIdentifierOrLiteral(name); } ts.getNameFromPropertyName = getNameFromPropertyName; @@ -87643,16 +90477,28 @@ var ts; QuotePreference[QuotePreference["Single"] = 0] = "Single"; QuotePreference[QuotePreference["Double"] = 1] = "Double"; })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function quotePreferenceFromString(str, sourceFile) { + return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; + } + ts.quotePreferenceFromString = quotePreferenceFromString; function getQuotePreference(sourceFile, preferences) { if (preferences.quotePreference) { return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; } else { - var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); - return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile) ? 0 /* Single */ : 1 /* Double */; + var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral); + return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */; } } ts.getQuotePreference = getQuotePreference; + function getQuoteFromPreference(qp) { + switch (qp) { + case 0 /* Single */: return "'"; + case 1 /* Double */: return '"'; + default: return ts.Debug.assertNever(qp); + } + } + ts.getQuoteFromPreference = getQuoteFromPreference; function symbolNameNoDefault(symbol) { var escaped = symbolEscapedNameNoDefault(symbol); return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); @@ -87710,25 +90556,6 @@ var ts; return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; } ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; - var NodeSet = /** @class */ (function () { - function NodeSet() { - this.map = ts.createMap(); - } - NodeSet.prototype.add = function (node) { - this.map.set(String(ts.getNodeId(node)), node); - }; - NodeSet.prototype.has = function (node) { - return this.map.has(String(ts.getNodeId(node))); - }; - NodeSet.prototype.forEach = function (cb) { - this.map.forEach(cb); - }; - NodeSet.prototype.some = function (pred) { - return ts.forEachEntry(this.map, pred) || false; - }; - return NodeSet; - }()); - ts.NodeSet = NodeSet; function getParentNodeInSpan(node, file, span) { if (!node) return undefined; @@ -87744,6 +90571,29 @@ var ts; return ts.textSpanContainsPosition(span, node.getStart(file)) && node.getEnd() <= ts.textSpanEnd(span); } + function findModifier(node, kind) { + return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + } + ts.findModifier = findModifier; + /* @internal */ + function insertImport(changes, sourceFile, importDecl) { + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + if (lastImportDeclaration) { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + } + else { + changes.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); + } + } + ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -87754,13 +90604,24 @@ var ts; ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios var displayParts; var lineStart; var indent; + var length; resetWriter(); var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { - displayParts: function () { return displayParts; }, + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, @@ -87789,23 +90650,35 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { + if (length > absoluteMaximumLength) + return; if (lineStart) { var indentString = ts.getIndentString(indent); if (indentString) { + length += indentString.length; displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); } lineStart = false; } } function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(displayPart(text, kind)); } function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(symbolPart(text, symbol)); } function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; displayParts.push(lineBreakPart()); lineStart = true; } @@ -87813,6 +90686,7 @@ var ts; displayParts = []; lineStart = true; indent = 0; + length = 0; } } function symbolPart(text, symbol) { @@ -87945,7 +90819,7 @@ var ts; ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { return !!location.parent && - (location.parent.kind === 248 /* ImportSpecifier */ || location.parent.kind === 252 /* ExportSpecifier */) && + (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -88006,24 +90880,49 @@ var ts; return clone; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; - function getSynthesizedDeepCloneWorker(node) { - var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone; + if (node && ts.isIdentifier(node) && renameMap && checker) { + var symbol = checker.getSymbolAtLocation(node); + var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); + if (renameInfo) { + clone = ts.createIdentifier(renameInfo.text); + } + } + if (!clone) { + clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + } + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + if (callback && node) + callback(node, clone); + return clone; + } + ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames; + function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) { + var visited = (renameMap || checker || callback) ? + ts.visitEachChild(node, wrapper, ts.nullTransformationContext) : + ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_1 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_1)) { - clone_1.textSourceNode = node; + var clone_7 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_7)) { + clone_7.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_1)) { - clone_1.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_7)) { + clone_7.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_1, node); + return ts.setTextRange(clone_7, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone // would have made. visited.parent = undefined; return visited; + function wrapper(node) { + return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback); + } } function getSynthesizedDeepClones(nodes, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = true; } @@ -88374,7 +91273,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_1 = 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) { @@ -88383,8 +91282,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_1, classification: convertClassification(type) }); - lastEnd = start + length_1; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -88563,10 +91462,10 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 239 /* ModuleDeclaration */: - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 234 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 237 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -88778,18 +91677,18 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 293 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 296 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 295 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 294 /* JSDocReturnTag */: + case 298 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -88876,22 +91775,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 257 /* JsxOpeningElement */: + case 260 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 258 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 256 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 262 /* JsxAttribute */: + case 265 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -88920,17 +91819,17 @@ var ts; var parent = token.parent; if (tokenKind === 58 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 232 /* VariableDeclaration */ || + if (parent.kind === 235 /* VariableDeclaration */ || parent.kind === 152 /* PropertyDeclaration */ || parent.kind === 149 /* Parameter */ || - parent.kind === 262 /* JsxAttribute */) { + parent.kind === 265 /* JsxAttribute */) { return 5 /* operator */; } } - if (parent.kind === 200 /* BinaryExpression */ || - parent.kind === 198 /* PrefixUnaryExpression */ || - parent.kind === 199 /* PostfixUnaryExpression */ || - parent.kind === 201 /* ConditionalExpression */) { + if (parent.kind === 202 /* BinaryExpression */ || + parent.kind === 200 /* PrefixUnaryExpression */ || + parent.kind === 201 /* PostfixUnaryExpression */ || + parent.kind === 203 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -88941,7 +91840,7 @@ var ts; } else if (tokenKind === 9 /* StringLiteral */) { // TODO: GH#18217 - return token.parent.kind === 262 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token.parent.kind === 265 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 12 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -88957,7 +91856,7 @@ var ts; else if (tokenKind === 71 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } @@ -88967,17 +91866,17 @@ var ts; return 15 /* typeParameterName */; } return; - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } @@ -89029,12 +91928,12 @@ var ts; }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { - return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(node, compilerOptions, host, typeChecker)); + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); } PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; - function getStringLiteralCompletionsFromModuleNamesWorker(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); - var scriptPath = node.getSourceFile().path; + var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); @@ -89046,7 +91945,6 @@ var ts; } } else { - // Check for node modules return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } @@ -89116,8 +92014,8 @@ var ts; * both foo.ts and foo.tsx become foo */ var foundFiles = ts.createMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var filePath = files_1[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; @@ -89163,7 +92061,7 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_1 = function (name, kind) { + var _loop_11 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind)); @@ -89171,7 +92069,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_1(name, kind); + _loop_11(name, kind); } } } @@ -89187,7 +92085,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_2 = function (moduleName) { + var _loop_12 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); @@ -89195,7 +92093,7 @@ var ts; }; for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { var moduleName = _f[_e]; - _loop_2(moduleName); + _loop_12(moduleName); } } if (!foundGlobal) { @@ -89212,14 +92110,16 @@ var ts; function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [{ name: path, kind: "directory" /* directory */ }] : ts.emptyArray; + return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); - if (!ts.startsWith(fragment, pathPrefix)) { - return [{ name: pathPrefix, kind: "directory" /* directory */ }]; + var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); + return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { + return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); + }); + function justPathMappingName(name) { + return ts.startsWith(name, fragment) ? [{ name: name, kind: "directory" /* directory */ }] : ts.emptyArray; } - var remainingFragment = fragment.slice(pathPrefix.length); - return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { if (!host.readDirectory) { @@ -89276,7 +92176,7 @@ var ts; return nonRelativeModuleNames; } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, position); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); if (!range) { @@ -89313,8 +92213,8 @@ var ts; } catch ( /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */_b) { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } if (typeRoots) { - for (var _c = 0, typeRoots_1 = typeRoots; _c < typeRoots_1.length; _c++) { - var root = typeRoots_1[_c]; + for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { + var root = typeRoots_2[_c]; getCompletionEntriesFromDirectories(root); } } @@ -89450,6 +92350,19 @@ var ts; (function (ts) { var Completions; (function (Completions) { + var SymbolOriginInfoKind; + (function (SymbolOriginInfoKind) { + SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 0] = "ThisType"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 1] = "SymbolMemberNoExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 2] = "SymbolMemberExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 3] = "Export"; + })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); + function originIsSymbolMember(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 1 /* SymbolMemberNoExport */; + } + function originIsExport(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 3 /* Export */; + } var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; @@ -89473,8 +92386,8 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) - return undefined; // TODO: GH#18217 + if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined @@ -89538,20 +92451,22 @@ var ts; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; - if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { + if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
- // The completion list at "1" will contain "div" with type any + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, - entries: [{ - name: tagName.getFullText(), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: "0", - }] }; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { @@ -89620,12 +92535,12 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (origin && origin.type === "this-type") { + if (origin && origin.kind === 0 /* ThisType */) { insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. - else if ((origin && origin.type === "symbol-member" || needsConvertPropertyAccess) && propertyAccessToConvert) { + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. @@ -89656,7 +92571,7 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(!!origin && origin.type === "export"), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), insertText: insertText, replacementSpan: replacementSpan, @@ -89682,7 +92597,7 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); @@ -89691,8 +92606,8 @@ var ts; // Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { @@ -89749,11 +92664,11 @@ var ts; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { switch (node.parent.kind) { - case 178 /* LiteralType */: + case 180 /* LiteralType */: switch (node.parent.parent.kind) { case 162 /* TypeReference */: return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; - case 176 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { // foo: string; @@ -89761,12 +92676,14 @@ var ts; // } // let x: Foo["/*completion position*/"] return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); - case 179 /* ImportType */: + case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 171 /* UnionType */: + return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; default: return undefined; } - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -89783,7 +92700,7 @@ var ts; return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); } return fromContextualType(); - case 186 /* ElementAccessExpression */: { + case 188 /* ElementAccessExpression */: { var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression @@ -89796,8 +92713,8 @@ var ts; } return undefined; } - case 187 /* CallExpression */: - case 188 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target @@ -89806,9 +92723,9 @@ var ts; return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); } // falls through (is `require("")` or `import("")`) - case 244 /* ImportDeclaration */: - case 250 /* ExportDeclaration */: - case 254 /* ExternalModuleReference */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 257 /* ExternalModuleReference */: // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // var y = import("/*completion position*/"); @@ -89879,13 +92796,13 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; } - function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, getCanonicalFileName, preferences, cancellationToken) { + function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var name = entryId.name; @@ -89914,7 +92831,7 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -89957,14 +92874,14 @@ var ts; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; } - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences) { + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo || symbolOriginInfo.type !== "export") { + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { return { codeActions: undefined, sourceDisplay: undefined }; } var moduleSymbol = symbolOriginInfo.moduleSymbol; var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { @@ -90005,11 +92922,11 @@ var ts; return getContextualTypeFromParent(previousToken, checker); case 58 /* EqualsToken */: switch (parent.kind) { - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 262 /* JsxAttribute */: + case 265 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; @@ -90019,7 +92936,7 @@ var ts; case 73 /* CaseKeyword */: return getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); case 17 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 255 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + return ts.isJsxExpression(parent) && parent.parent.kind !== 258 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo @@ -90034,15 +92951,15 @@ var ts; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { - case 188 /* NewExpression */: + case 190 /* NewExpression */: return checker.getContextualType(parent); - case 200 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node); } - case 266 /* CaseClause */: + case 269 /* CaseClause */: return parent.expression === node ? getSwitchedType(parent, checker) : undefined; default: return checker.getContextualType(node); @@ -90058,16 +92975,15 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 274 /* SourceFile */; }); + return symbol.declarations.some(function (d) { return d.kind === 277 /* SourceFile */; }); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 + var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); - // Completion not allowed inside comments, bail out if this is the case var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); var insideJsDocTagTypeExpression = false; @@ -90110,11 +93026,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 278 /* JSDocTypeExpression */) { - currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 281 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 298 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 303 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -90132,7 +93048,7 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217 + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file @@ -90140,9 +93056,9 @@ var ts; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { - var start_1 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217 - log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); + var start_4 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -90164,15 +93080,18 @@ var ts; if (contextToken.kind === 23 /* DotToken */) { isRightOfDot = true; switch (parent.kind) { - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; break; case 146 /* QualifiedName */: node = parent.left; break; - case 179 /* ImportType */: - case 210 /* MetaProperty */: + case 242 /* ModuleDeclaration */: + node = parent.name; + break; + case 181 /* ImportType */: + case 212 /* MetaProperty */: node = parent; break; default: @@ -90185,7 +93104,7 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 185 /* PropertyAccessExpression */) { + if (parent && parent.kind === 187 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } @@ -90193,39 +93112,38 @@ var ts; if (currentToken.parent === location) { switch (currentToken.kind) { case 29 /* GreaterThanToken */: - if (currentToken.parent.kind === 255 /* JsxElement */ || currentToken.parent.kind === 257 /* JsxOpeningElement */) { + if (currentToken.parent.kind === 258 /* JsxElement */ || currentToken.parent.kind === 260 /* JsxOpeningElement */) { location = currentToken; } break; case 41 /* SlashToken */: - if (currentToken.parent.kind === 256 /* JsxSelfClosingElement */) { + if (currentToken.parent.kind === 259 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 258 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: if (contextToken.kind === 41 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 200 /* BinaryExpression */: - if (!(parent.left.flags & 32768 /* ThisNodeHasError */)) { - // It has a left-hand side, so we're not in an opening JSX tag. + case 202 /* BinaryExpression */: + if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 256 /* JsxSelfClosingElement */: - case 255 /* JsxElement */: - case 257 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 258 /* JsxElement */: + case 260 /* JsxOpeningElement */: if (contextToken.kind === 27 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 262 /* JsxAttribute */: + case 265 /* JsxAttribute */: switch (previousToken.kind) { case 58 /* EqualsToken */: isJsxInitializer = true; @@ -90278,11 +93196,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 293 /* JSDocParameterTag */: - case 298 /* JSDocPropertyTag */: - case 294 /* JSDocReturnTag */: - case 295 /* JSDocTypeTag */: - case 297 /* JSDocTypedefTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: + case 298 /* JSDocReturnTag */: + case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypedefTag */: return true; default: return false; @@ -90295,8 +93213,11 @@ var ts; var isImportType = ts.isLiteralImportTypeNode(node); var isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !node.isTypeOf) || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); - var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile)); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)); if (ts.isEntityName(node) || isImportType) { + var isNamespaceName = ts.isModuleDeclaration(node.parent); + if (isNamespaceName) + isNewIdentifierLocation = true; var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { symbol = ts.skipAlias(symbol, typeChecker); @@ -90305,18 +93226,21 @@ var ts; var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; - var isValidAccess = allowTypeOrValue ? - // Any kind is allowed when dotting off namespace in internal import equals declaration - function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : - isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + var isValidAccess = isNamespaceName + // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. + ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + : allowTypeOrValue ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { - var symbol_1 = exportedSymbols_1[_i]; - if (isValidAccess(symbol_1)) { - symbols.push(symbol_1); + var exportedSymbol = exportedSymbols_1[_i]; + if (isValidAccess(exportedSymbol)) { + symbols.push(exportedSymbol); } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 274 /* SourceFile */ && d.kind !== 239 /* ModuleDeclaration */ && d.kind !== 238 /* EnumDeclaration */; })) { + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 277 /* SourceFile */ && d.kind !== 242 /* ModuleDeclaration */ && d.kind !== 241 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -90340,27 +93264,33 @@ var ts; // each individual type has. This is because we're going to add all identifiers // anyways. So we might as well elevate the members that were at least part // of the individual types to a higher status since we know what they are. - symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true)); + symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker)); } else { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 179 /* ImportType */ ? node : node.parent, type, symbol)) { + if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 181 /* ImportType */ ? node : node.parent, type, symbol)) { addPropertySymbol(symbol); } } } } function addPropertySymbol(symbol) { + // For a computed property with an accessible name like `Symbol.iterator`, + // we'll add a completion for the *name* `Symbol` instead of for the property. // If this is e.g. [Symbol.iterator], add a completion for `Symbol`. - var symbolSymbol = ts.firstDefined(symbol.declarations, function (decl) { - var name = ts.getNameOfDeclaration(decl); - var leftName = name.kind === 147 /* ComputedPropertyName */ ? getLeftMostName(name.expression) : undefined; - return leftName && typeChecker.getSymbolAtLocation(leftName); - }); - if (symbolSymbol) { - symbols.push(symbolSymbol); - symbolToOriginInfoMap[ts.getSymbolId(symbolSymbol)] = { type: "symbol-member" }; + var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); }); + if (computedPropertyName) { + var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`. + var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); + // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. + var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); + if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { + symbols.push(firstAccessibleSymbol); + var moduleSymbol = firstAccessibleSymbol.parent; + symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = + !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) ? { kind: 1 /* SymbolMemberNoExport */ } : { kind: 2 /* SymbolMemberExport */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } } else { symbols.push(symbol); @@ -90444,12 +93374,12 @@ var ts; var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 274 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode); if (thisType) { - for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 0 /* ThisType */ }; symbols.push(symbol); } } @@ -90480,10 +93410,10 @@ var ts; } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 274 /* SourceFile */: - case 202 /* TemplateExpression */: - case 265 /* JsxExpression */: - case 213 /* Block */: + case 277 /* SourceFile */: + case 204 /* TemplateExpression */: + case 268 /* JsxExpression */: + case 216 /* Block */: return true; default: return ts.isStatement(scopeNode); @@ -90491,7 +93421,7 @@ var ts; } function filterGlobalCompletion(symbols) { var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile); + var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) keywordFilters = 5 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { @@ -90530,12 +93460,12 @@ var ts; return parentKind === 152 /* PropertyDeclaration */ || parentKind === 151 /* PropertySignature */ || parentKind === 149 /* Parameter */ || - parentKind === 232 /* VariableDeclaration */ || + parentKind === 235 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); case 58 /* EqualsToken */: - return parentKind === 237 /* TypeAliasDeclaration */; + return parentKind === 240 /* TypeAliasDeclaration */; case 118 /* AsKeyword */: - return parentKind === 208 /* AsExpression */; + return parentKind === 210 /* AsExpression */; } } return false; @@ -90584,7 +93514,7 @@ var ts; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + var origin = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; @@ -90638,11 +93568,11 @@ var ts; return true; } if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 257 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 260 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 258 /* JsxClosingElement */ || contextToken.parent.kind === 256 /* JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 255 /* JsxElement */; + if (contextToken.parent.kind === 261 /* JsxClosingElement */ || contextToken.parent.kind === 259 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 258 /* JsxElement */; } } return false; @@ -90650,50 +93580,44 @@ var ts; function isNewIdentifierDefinitionLocation(previousToken) { if (previousToken) { var containingNodeKind = previousToken.parent.kind; - switch (previousToken.kind) { + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(previousToken)) { case 26 /* CommaToken */: - return containingNodeKind === 187 /* CallExpression */ // func( a, | + return containingNodeKind === 189 /* CallExpression */ // func( a, | || containingNodeKind === 155 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 188 /* NewExpression */ // new C(a, | - || containingNodeKind === 183 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 200 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 190 /* NewExpression */ // new C(a, | + || containingNodeKind === 185 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 202 /* BinaryExpression */ // const x = (a, | || containingNodeKind === 163 /* FunctionType */; // var x: (s: string, list| case 19 /* OpenParenToken */: - return containingNodeKind === 187 /* CallExpression */ // func( | + return containingNodeKind === 189 /* CallExpression */ // func( | || containingNodeKind === 155 /* Constructor */ // constructor( | - || containingNodeKind === 188 /* NewExpression */ // new C(a| - || containingNodeKind === 191 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 173 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + || containingNodeKind === 190 /* NewExpression */ // new C(a| + || containingNodeKind === 193 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 175 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 21 /* OpenBracketToken */: - return containingNodeKind === 183 /* ArrayLiteralExpression */ // [ | + return containingNodeKind === 185 /* ArrayLiteralExpression */ // [ | || containingNodeKind === 160 /* IndexSignature */ // [ | : string ] || containingNodeKind === 147 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 129 /* ModuleKeyword */: // module | case 130 /* NamespaceKeyword */: // namespace | return true; case 23 /* DotToken */: - return containingNodeKind === 239 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 242 /* ModuleDeclaration */; // module A.| case 17 /* OpenBraceToken */: - return containingNodeKind === 235 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 238 /* ClassDeclaration */; // class A{ | case 58 /* EqualsToken */: - return containingNodeKind === 232 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 200 /* BinaryExpression */; // x = a| + return containingNodeKind === 235 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 202 /* BinaryExpression */; // x = a| case 14 /* TemplateHead */: - return containingNodeKind === 202 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 204 /* TemplateExpression */; // `aa ${| case 15 /* TemplateMiddle */: - return containingNodeKind === 211 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 214 /* TemplateSpan */; // `aa ${10} dd ${| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: return containingNodeKind === 152 /* PropertyDeclaration */; // class A{ public | } - // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: - return true; - } } return false; } @@ -90719,16 +93643,16 @@ var ts; completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 184 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 186 /* ObjectLiteralExpression */) { var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return 2 /* Fail */; isNewIdentifierLocation = hasIndexSignature(typeForObject); - typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false); + typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); existingMembers = objectLikeContainer.properties; } else { - ts.Debug.assert(objectLikeContainer.kind === 180 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 182 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -90739,7 +93663,7 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 222 /* ForOfStatement */; + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 225 /* ForOfStatement */; if (!canGetType && rootDeclaration.kind === 149 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); @@ -90786,7 +93710,7 @@ var ts; return 0 /* Continue */; // cursor is in an import clause // try to show exported member for imported module - var moduleSpecifier = (namedImportsOrExports.kind === 247 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 250 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -90830,8 +93754,8 @@ var ts; if (!(classElementModifierFlags & 8 /* Private */)) { // List of property symbols of base type that are not private and already implemented var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { - var type = typeChecker.getTypeAtLocation(baseTypeNode); // TODO: GH#18217 - return typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); + var type = typeChecker.getTypeAtLocation(baseTypeNode); + return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type); }); symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags); } @@ -90901,14 +93825,14 @@ var ts; case 28 /* LessThanSlashToken */: case 41 /* SlashToken */: case 71 /* Identifier */: - case 185 /* PropertyAccessExpression */: - case 263 /* JsxAttributes */: - case 262 /* JsxAttribute */: - case 264 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 256 /* JsxSelfClosingElement */ || parent.kind === 257 /* JsxOpeningElement */)) { + case 187 /* PropertyAccessExpression */: + case 266 /* JsxAttributes */: + case 265 /* JsxAttribute */: + case 267 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 259 /* JsxSelfClosingElement */ || parent.kind === 260 /* JsxOpeningElement */)) { return parent; } - else if (parent.kind === 262 /* JsxAttribute */) { + else if (parent.kind === 265 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -90920,7 +93844,7 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent && ((parent.kind === 262 /* JsxAttribute */) || (parent.kind === 264 /* JsxSpreadAttribute */))) { + if (parent && ((parent.kind === 265 /* JsxAttribute */) || (parent.kind === 267 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -90930,8 +93854,8 @@ var ts; break; case 18 /* CloseBraceToken */: if (parent && - parent.kind === 265 /* JsxExpression */ && - parent.parent && parent.parent.kind === 262 /* JsxAttribute */) { + parent.kind === 268 /* JsxExpression */ && + parent.parent && parent.parent.kind === 265 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -90939,7 +93863,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 264 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 267 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -90959,49 +93883,49 @@ var ts; var containingNodeKind = parent.kind; switch (contextToken.kind) { case 26 /* CommaToken */: - return containingNodeKind === 232 /* VariableDeclaration */ || - containingNodeKind === 233 /* VariableDeclarationList */ || - containingNodeKind === 214 /* VariableStatement */ || - containingNodeKind === 238 /* EnumDeclaration */ || // enum a { foo, | + return containingNodeKind === 235 /* VariableDeclaration */ || + containingNodeKind === 236 /* VariableDeclarationList */ || + containingNodeKind === 217 /* VariableStatement */ || + containingNodeKind === 241 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 236 /* InterfaceDeclaration */ || // interface A= contextToken.pos); case 23 /* DotToken */: - return containingNodeKind === 181 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 183 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: - return containingNodeKind === 182 /* BindingElement */; // var {x :html| + return containingNodeKind === 184 /* BindingElement */; // var {x :html| case 21 /* OpenBracketToken */: - return containingNodeKind === 181 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 183 /* ArrayBindingPattern */; // var [x| case 19 /* OpenParenToken */: - return containingNodeKind === 269 /* CatchClause */ || + return containingNodeKind === 272 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: - return containingNodeKind === 238 /* EnumDeclaration */; // enum a { | + return containingNodeKind === 241 /* EnumDeclaration */; // enum a { | case 27 /* LessThanToken */: - return containingNodeKind === 235 /* ClassDeclaration */ || // class A< | - containingNodeKind === 205 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 236 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 237 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 238 /* ClassDeclaration */ || // class A< | + containingNodeKind === 207 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 240 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: return containingNodeKind === 152 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 24 /* DotDotDotToken */: return containingNodeKind === 149 /* Parameter */ || - (!!parent.parent && parent.parent.kind === 181 /* ArrayBindingPattern */); // var [...z| + (!!parent.parent && parent.parent.kind === 183 /* ArrayBindingPattern */); // var [...z| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: return containingNodeKind === 149 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 118 /* AsKeyword */: - return containingNodeKind === 248 /* ImportSpecifier */ || - containingNodeKind === 252 /* ExportSpecifier */ || - containingNodeKind === 246 /* NamespaceImport */; + return containingNodeKind === 251 /* ImportSpecifier */ || + containingNodeKind === 255 /* ExportSpecifier */ || + containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: if (isFromObjectTypeDeclaration(contextToken)) { @@ -91085,9 +94009,9 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 270 /* PropertyAssignment */ && - m.kind !== 271 /* ShorthandPropertyAssignment */ && - m.kind !== 182 /* BindingElement */ && + if (m.kind !== 273 /* PropertyAssignment */ && + m.kind !== 274 /* ShorthandPropertyAssignment */ && + m.kind !== 184 /* BindingElement */ && m.kind !== 154 /* MethodDeclaration */ && m.kind !== 156 /* GetAccessor */ && m.kind !== 157 /* SetAccessor */) { @@ -91109,7 +94033,7 @@ var ts; // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. var name = ts.getNameOfDeclaration(m); - existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } existingMemberNames.set(existingName, true); // TODO: GH#18217 } @@ -91168,7 +94092,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 262 /* JsxAttribute */) { + if (attr.kind === 265 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } @@ -91236,7 +94160,7 @@ var ts; case 3 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); case 4 /* FunctionLikeBodyKeywords */: - return !isClassMemberCompletionKeyword(kind); + return isFunctionLikeBodyKeyword(kind); case 5 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: @@ -91259,6 +94183,9 @@ var ts; return ts.isClassMemberModifier(kind); } } + function isFunctionLikeBodyKeyword(kind) { + return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } @@ -91275,47 +94202,28 @@ var ts; } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { - var jsDoc = getJsDocHavingNode(node).jsDoc; - if (!jsDoc) - return undefined; - for (var _i = 0, jsDoc_1 = jsDoc; _i < jsDoc_1.length; _i++) { - var _a = jsDoc_1[_i], pos = _a.pos, end = _a.end, tags = _a.tags; - if (!tags || position < pos || position > end) - continue; - for (var i = tags.length - 1; i >= 0; i--) { - var tag = tags[i]; - if (position >= tag.pos) { - return tag; - } - } - } + var jsdoc = ts.findAncestor(node, ts.isJSDoc); + return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined); } - function getJsDocHavingNode(node) { - if (!ts.isToken(node)) - return node; - switch (node.kind) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - // if the current token is var, let or const, skip the VariableDeclarationList - return node.parent.parent; - default: - return node.parent; - } + function getPropertiesForObjectExpression(contextualType, obj, checker) { + return contextualType.isUnion() + ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + return !(memberType.flags & 32764 /* Primitive */ || + checker.isArrayLikeType(memberType) || + ts.typeHasCallOrConstructSignatures(memberType, checker) || + checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); + })) + : contextualType.getApparentProperties(); } /** * Gets all properties on a type, but if that type is a union of several types, * excludes array-like types or callable/constructable types. */ - function getPropertiesForCompletion(type, checker, isForAccess) { - if (!(type.isUnion())) { - return ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); - } - // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. - var filteredTypes = isForAccess ? type.types : type.types.filter(function (memberType) { - return !(memberType.flags & 32764 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker)); - }); - return ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(filteredTypes), "getAllPossiblePropertiesOfTypes() should all be defined"); + function getPropertiesForCompletion(type, checker) { + return type.isUnion() + ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") + : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); } /** * Returns the immediate owning class declaration of a context token, @@ -91324,7 +94232,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 299 /* SyntaxList */: + case 304 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -91371,7 +94279,7 @@ var ts; return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 200 /* BinaryExpression */; + return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": return ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) @@ -91380,12 +94288,16 @@ var ts; return ts.Debug.assertNever(triggerCharacter); } } + function binaryExpressionMayBeOpenTag(_a) { + var left = _a.left; + return ts.nodeIsMissing(left); + } function isStringLiteralOrTemplate(node) { switch (node.kind) { case 9 /* StringLiteral */: case 13 /* NoSubstitutionTemplateLiteral */: - case 202 /* TemplateExpression */: - case 189 /* TaggedTemplateExpression */: + case 204 /* TemplateExpression */: + case 191 /* TaggedTemplateExpression */: return true; default: return false; @@ -91428,7 +94340,7 @@ var ts; return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; if (!sourceFilesSet.has(fileName)) { - ts.Debug.assert(program.redirectTargetsSet.has(fileName)); + ts.Debug.assert(program.redirectTargetsMap.has(fileName)); var redirectTarget_1 = program.getSourceFile(fileName); var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; @@ -91519,7 +94431,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 274 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 277 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -91551,16 +94463,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 227 /* SwitchStatement */: - if (statement.kind === 223 /* ContinueStatement */) { + case 230 /* SwitchStatement */: + if (statement.kind === 226 /* ContinueStatement */) { return false; } // falls through - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 219 /* WhileStatement */: - case 218 /* DoStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 222 /* WhileStatement */: + case 221 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -91570,24 +94482,17 @@ var ts; }); } function getModifierOccurrences(modifier, declaration) { - var modifierFlag = ts.modifierToFlag(modifier); - return ts.mapDefined(getNodesToSearchForModifier(declaration, modifierFlag), function (node) { - if (ts.getModifierFlags(node) & modifierFlag) { - var mod = ts.find(node.modifiers, function (m) { return m.kind === modifier; }); - ts.Debug.assert(!!mod); - return mod; - } - }); + return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); }); } function getNodesToSearchForModifier(declaration, modifierFlag) { // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 240 /* ModuleBlock */: - case 274 /* SourceFile */: - case 213 /* Block */: - case 266 /* CaseClause */: - case 267 /* DefaultClause */: + case 243 /* ModuleBlock */: + case 277 /* SourceFile */: + case 216 /* Block */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return declaration.members.concat([declaration]); @@ -91597,10 +94502,10 @@ var ts; } case 155 /* Constructor */: case 154 /* MethodDeclaration */: - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -91633,7 +94538,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 218 /* DoStatement */) { + if (loopNode.kind === 221 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { @@ -91653,13 +94558,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 218 /* DoStatement */: - case 219 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -92031,12 +94936,13 @@ var ts; if (!markSeenDirectImport(direct)) { continue; } - cancellationToken.throwIfCancellationRequested(); + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 187 /* CallExpression */: + case 189 /* CallExpression */: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 232 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 235 /* VariableDeclaration */) { var name = parent.name; if (name.kind === 71 /* Identifier */) { directImports.push(name); @@ -92049,26 +94955,20 @@ var ts; break; case 71 /* Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 243 /* ImportEqualsDeclaration */: - handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */)); + case 246 /* ImportEqualsDeclaration */: + handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: + directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 246 /* NamespaceImport */) { - handleNamespaceImport(direct, namedBindings.name); + if (namedBindings && namedBindings.kind === 249 /* NamespaceImport */) { + handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } - else if (ts.isDefaultImport(direct)) { - var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); - if (!isAvailableThroughGlobal) { - addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports - } - directImports.push(direct); - } - else { - directImports.push(direct); + else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { + addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); @@ -92078,7 +94978,7 @@ var ts; directImports.push(direct); } break; - case 179 /* ImportType */: + case 181 /* ImportType */: directImports.push(direct); break; default: @@ -92087,14 +94987,15 @@ var ts; } } } - function handleNamespaceImport(importDeclaration, name, isReExport) { + function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { if (exportKind === 2 /* ExportEquals */) { // This is a direct import, not import-as-namespace. - directImports.push(importDeclaration); + if (!alreadyAddedDirect) + directImports.push(importDeclaration); } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 274 /* SourceFile */ || sourceFileLike.kind === 239 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 277 /* SourceFile */ || sourceFileLike.kind === 242 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -92149,7 +95050,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 243 /* ImportEqualsDeclaration */) { + if (decl.kind === 246 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -92159,7 +95060,7 @@ var ts; handleNamespaceImportLike(decl); return; } - if (decl.kind === 179 /* ImportType */) { + if (decl.kind === 181 /* ImportType */) { if (decl.qualifier) { if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { singleReferences.push(decl.qualifier); @@ -92174,36 +95075,33 @@ var ts; if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { return; } - if (decl.kind === 250 /* ExportDeclaration */) { + if (decl.kind === 253 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } - var importClause = decl.importClause; - if (!importClause) { - return; - } - var namedBindings = importClause.namedBindings; - if (namedBindings && namedBindings.kind === 246 /* NamespaceImport */) { - handleNamespaceImportLike(namedBindings.name); - return; - } - if (exportKind === 0 /* Named */) { - searchForNamedImport(namedBindings); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) - } - else { - // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals - var name = importClause.name; - // If a default import has the same name as the default export, allow to rename it. - // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. - if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { - var defaultImportAlias = checker.getSymbolAtLocation(name); - addSearch(name, defaultImportAlias); - } - // 'default' might be accessed as a named import `{ default as foo }`. - if (exportKind === 1 /* Default */) { - searchForNamedImport(namedBindings); + var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 249 /* NamespaceImport */: + handleNamespaceImportLike(namedBindings.name); + break; + case 250 /* NamedImports */: + // 'default' might be accessed as a named import `{ default as foo }`. + if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { + searchForNamedImport(namedBindings); + } + break; + default: + ts.Debug.assertNever(namedBindings); } } + // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals. + // If a default import has the same name as the default export, allow to rename it. + // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. + if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); + } } /** * `import x = require("./x") or `import * as x from "./x"`. @@ -92237,7 +95135,7 @@ var ts; } } else { - var localSymbol = element.kind === 252 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 255 /* 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); @@ -92263,10 +95161,10 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var referencingFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var referencingFile = sourceFiles_5[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 274 /* SourceFile */) { + if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -92294,9 +95192,10 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; - cancellationToken.throwIfCancellationRequested(); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); if (moduleSymbol) { @@ -92313,7 +95212,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 274 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 277 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -92328,15 +95227,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 250 /* ExportDeclaration */: - case 244 /* ImportDeclaration */: { + case 253 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 243 /* ImportEqualsDeclaration */: { + case 246 /* ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -92360,7 +95259,7 @@ var ts; var parent = node.parent; var grandParent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 185 /* PropertyAccessExpression */) { + if (parent.kind === 187 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) @@ -92482,10 +95381,10 @@ var ts; // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 232 /* VariableDeclaration */) { + if (parent.kind === 235 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 269 /* CatchClause */ ? undefined : p.parent.parent.kind === 214 /* VariableStatement */ ? p.parent.parent : undefined; + p.parent.kind === 272 /* CatchClause */ ? undefined : p.parent.parent.kind === 217 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -92494,15 +95393,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 248 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return parent.propertyName ? undefined : { isNamedImport: true }; - case 245 /* ImportClause */: - case 246 /* NamespaceImport */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -92535,21 +95434,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 187 /* CallExpression */) { + if (node.kind === 189 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 274 /* SourceFile */) { + if (parent.kind === 277 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 240 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 243 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 239 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; + return node.kind === 242 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 254 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */; + return eq.moduleReference.kind === 257 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -92584,16 +95483,16 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 274 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 271 /* ShorthandPropertyAssignment */) { - var result_1 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); }); - return result_1; + if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + var result_6 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); + return result_6; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -92606,8 +95505,7 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var node = ts.getTouchingPropertyName(sourceFile, position); + function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; @@ -92626,27 +95524,27 @@ var ts; case "symbol": { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_1 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 }; + var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } case "label": { - var node_1 = def.node; - return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] }; + var node_3 = def.node; + return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { - var node_2 = def.node; - var name_2 = ts.tokenToString(node_2.kind); - return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* 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 */ }] }; } case "this": { - var node_3 = def.node; - var symbol = checker.getSymbolAtLocation(node_3); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")]; - return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; + var node_5 = def.node; + var symbol = checker.getSymbolAtLocation(node_5); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; + return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { - var node_4 = def.node; - return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] }; + var node_6 = def.node; + return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } default: return ts.Debug.assertNever(def); @@ -92694,13 +95592,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 184 /* ObjectLiteralExpression */) { + else if (node.kind === 186 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] }; } - else if (node.kind === 205 /* ClassExpression */) { + else if (node.kind === 207 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] @@ -92754,7 +95652,8 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -92813,10 +95712,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 274 /* SourceFile */: + case 277 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { references.push({ type: "node", node: decl.name }); } @@ -92974,7 +95873,7 @@ var ts; this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); }; - /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ + /** @param allSearchSymbols set of additional symbols for use by `includes`. */ State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. @@ -93011,8 +95910,8 @@ var ts; var sourceId = ts.getNodeId(sourceFile); var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap()); var anyNewSymbols = false; - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var sym = symbols_2[_i]; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var sym = symbols_4[_i]; anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; } return anyNewSymbols; @@ -93057,6 +95956,24 @@ var ts; } } } + function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { + var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken); + var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers; + for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) { + var importLocation = importSearches_2[_i][0]; + cb(importLocation); + } + for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) { + var indirectUser = indirectUsers_2[_b]; + for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { + var node = _d[_c]; + if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) { + cb(node); + } + } + } + } + Core.eachExportReference = eachExportReference; function shouldAddSingleReference(singleRef, state) { if (!hasMatchingMeaning(singleRef, state)) return false; @@ -93089,9 +96006,9 @@ var ts; : undefined; } function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 182 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); if (bindingElement && - bindingElement.parent.kind === 180 /* ObjectBindingPattern */ && + bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && ts.isIdentifier(bindingElement.name) && !bindingElement.propertyName) { return bindingElement; @@ -93113,7 +96030,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 192 /* FunctionExpression */ || valueDeclaration.kind === 205 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 194 /* FunctionExpression */ || valueDeclaration.kind === 207 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -93123,7 +96040,7 @@ var ts; if (flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 235 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 238 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -93141,18 +96058,18 @@ var ts; - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. */ var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); - if (exposedByParent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } var scope; - for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { - var declaration = declarations_1[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 274 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -93191,6 +96108,28 @@ var ts; } } Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; + function eachSignatureCall(signature, sourceFiles, checker, cb) { + if (!signature.name || !ts.isIdentifier(signature.name)) + return; + var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { + var name = _b[_a]; + if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) + continue; + var called = ts.climbPastPropertyAccess(name); + var call = called.parent; + if (!ts.isCallExpression(call) || call.expression !== called) + continue; + var referenceSymbol = checker.getSymbolAtLocation(name); + if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) { + cb(call); + } + } + } + } + Core.eachSignatureCall = eachSignatureCall; function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); }); @@ -93415,6 +96354,7 @@ var ts; function getReferenceForShorthandProperty(_a, search, state) { var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); + var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration); /* * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment * has two meanings: property name and property value. Therefore when we do findAllReference at the position where @@ -93422,8 +96362,8 @@ var ts; * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the * position of property accessing, the referenceEntry of such position will be handled in the first case. */ - if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state); + if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) { + addReference(name, shorthandValueSymbol, state); } } function addReference(referenceLocation, relatedSymbol, state) { @@ -93531,7 +96471,7 @@ var ts; if (refNode.kind !== 71 /* Identifier */) { return; } - if (refNode.parent.kind === 271 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 274 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -93551,7 +96491,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 213 /* Block */) { + if (body.kind === 216 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -93579,13 +96519,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 191 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 193 /* ArrowFunction */: - case 192 /* FunctionExpression */: - case 184 /* ObjectLiteralExpression */: - case 205 /* ClassExpression */: - case 183 /* ArrayLiteralExpression */: + case 195 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 186 /* ObjectLiteralExpression */: + case 207 /* ClassExpression */: + case 185 /* ArrayLiteralExpression */: return true; default: return false; @@ -93683,20 +96623,20 @@ var ts; staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 274 /* SourceFile */: + case 277 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // falls through - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 274 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 277 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -93704,19 +96644,19 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 192 /* FunctionExpression */: - case 234 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 205 /* ClassExpression */: - case 235 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; - case 274 /* SourceFile */: - return container.kind === 274 /* SourceFile */ && !ts.isExternalModule(container); + case 277 /* SourceFile */: + return container.kind === 277 /* SourceFile */ && !ts.isExternalModule(container); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); @@ -93751,7 +96691,8 @@ var ts; // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - var res_1 = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), fromRoot); + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); if (res_1) return res_1; // If the location is name of property symbol from object literal destructuring pattern @@ -93816,14 +96757,6 @@ var ts; return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); }); } - /** Gets all symbols for one property. Does not get symbols for every property. */ - function getPropertySymbolsFromContextualType(node, checker) { - var contextualType = checker.getContextualType(node.parent); - var name = ts.getNameFromPropertyName(node.name); - var symbol = contextualType && name && contextualType.getProperty(name); - return symbol ? [symbol] : - contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; // TODO: GH#18217 - } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class @@ -93844,8 +96777,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { - var declaration = declarations_2[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -93907,26 +96840,39 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName); - var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); }); } ts.getEditsForFileRename = getEditsForFileRename; - function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName) { + // exported for tests + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return function (path) { - var canonicalPath = getCanonicalFileName(path); - if (canonicalPath === canonicalOldPath) + var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) return newFileOrDirPath; - var suffix = ts.tryRemoveDirectoryPrefix(canonicalPath, canonicalOldPath); + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; - }; + } + } + ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); } function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; @@ -93976,8 +96922,8 @@ var ts; // Type annotation needed due to #7294 var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; var foundExactMatch = false; - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var element = elements_1[_i]; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; foundExactMatch = tryUpdateString(element) || foundExactMatch; } return foundExactMatch; @@ -93998,12 +96944,15 @@ var ts; } } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { - var _loop_3 = function (sourceFile) { - var newImportFromPath = oldToNew(sourceFile.fileName) || sourceFile.fileName; + var allFiles = program.getSourceFiles(); + var _loop_13 = function (sourceFile) { + var newFromOld = oldToNew(sourceFile.path); + var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); var oldFromNew = newToOld(sourceFile.fileName); var oldImportFromPath = oldFromNew || sourceFile.fileName; var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined; updateImportsWorker(sourceFile, changeTracker, function (referenceText) { if (!ts.pathIsRelative(referenceText)) return undefined; @@ -94011,17 +96960,24 @@ var ts; var newAbsolute = oldToNew(oldAbsolute); return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); }, function (importLiteral) { + var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + // No need to update if it's an ambient module^M + if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. // TODO:GH#18217 - ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, program) - : getSourceFileToImport(importLiteral, sourceFile, program, host, oldToNew); - return toImport === undefined ? undefined : ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport, host, preferences); + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); + // Need an update if the imported file moved, or the importing file moved and was using a relative path. + return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) + ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + : undefined; }); }; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - _loop_3(sourceFile); + for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { + var sourceFile = allFiles_1[_i]; + _loop_13(sourceFile); } } function combineNormal(pathA, pathB) { @@ -94030,27 +96986,26 @@ var ts; function combinePathsSafe(pathA, pathB) { return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); } - function getSourceFileToImport(importLiteral, importingSourceFile, program, host, oldToNew) { - var symbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); - if (symbol) { - if (symbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) - return undefined; // No need to update if it's an ambient module - var oldFileName = ts.find(symbol.declarations, ts.isSourceFile).fileName; - return oldToNew(oldFileName) || oldFileName; + function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) { + if (importedModuleSymbol) { + // `find` should succeed because we checked for ambient modules before calling this function. + var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName; + var newFileName = oldToNew(oldFileName); + return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true }; } else { var resolved = host.resolveModuleNames ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); - return getSourceFileToImportFromResolved(resolved, oldToNew, program); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); } } - function getSourceFileToImportFromResolved(resolved, oldToNew, program) { - return resolved && ((resolved.resolvedModule && getIfInProgram(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfInProgram)); - function getIfInProgram(oldLocation) { + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); + function getIfExists(oldLocation) { var newLocation = oldToNew(oldLocation); - return program.getSourceFile(oldLocation) || newLocation !== undefined && program.getSourceFile(newLocation) - ? newLocation || oldLocation + return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 + ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } : undefined; } } @@ -94110,17 +97065,18 @@ var ts; return getDefinitionInfoForIndexSignatures(node, typeChecker); } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); - if (calledDeclaration) { + // Don't go to the component constructor definition for a JSX element, just go to the component definition. + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || - // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias - symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { return [sigInfo]; } else { - var defs = getDefinitionFromSymbol(typeChecker, symbol, node); + var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; // For a 'super()' call, put the signature first, else put the variable first. return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } @@ -94130,7 +97086,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 271 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; } @@ -94147,13 +97103,12 @@ var ts; // bar(({pr/*goto*/op1})=>{}); if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && (node === (parent.propertyName || parent.name))) { + var name_5 = ts.getNameFromPropertyName(node); var type = typeChecker.getTypeAtLocation(parent.parent); - if (type) { - var propSymbols = ts.getPropertySymbolsFromType(type, node); - if (propSymbols) { - return ts.flatMap(propSymbols, function (propSymbol) { return getDefinitionFromSymbol(typeChecker, propSymbol, node); }); - } - } + return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_5); + return prop && getDefinitionFromSymbol(typeChecker, prop, node); + }); } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. @@ -94165,10 +97120,13 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element && typeChecker.getContextualType(element.parent)) { - return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { - return getDefinitionFromSymbol(typeChecker, propertySymbol, node); - }); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -94179,7 +97137,7 @@ var ts; */ function symbolMatchesSignature(s, calledDeclaration) { return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || - ts.isVariableDeclaration(calledDeclaration.parent) && s === calledDeclaration.parent.symbol; + !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol; } function getReferenceAtPosition(sourceFile, position, program) { var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); @@ -94208,16 +97166,32 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); - if (!type) { + if (!symbol) return undefined; - } - if (type.isUnion() && !(type.flags & 32 /* Enum */)) { - return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); - } - return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); + var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); + var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); + // If a function returns 'void' or some other type with no definition, just return the function definition. + return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function definitionFromType(type, checker, node) { + return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) { + return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node); + }); + } + function tryGetReturnTypeOfFunction(symbol, type, checker) { + // If the type is just a function's inferred type, + // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway. + if (type.symbol === symbol || + // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { + var sigs = type.getCallSignatures(); + if (sigs.length === 1) + return checker.getReturnTypeOfSignature(ts.first(sigs)); + } + return undefined; + } function getDefinitionAndBoundSpan(program, sourceFile, position) { var definitions = getDefinitionAtPosition(program, sourceFile, position); if (!definitions || definitions.length === 0) { @@ -94272,11 +97246,11 @@ var ts; return true; } switch (declaration.kind) { - case 245 /* ImportClause */: - case 243 /* ImportEqualsDeclaration */: + case 248 /* ImportClause */: + case 246 /* ImportEqualsDeclaration */: return true; - case 248 /* ImportSpecifier */: - return declaration.parent.kind === 247 /* NamedImports */; + case 251 /* ImportSpecifier */: + return declaration.parent.kind === 250 /* NamedImports */; default: return false; } @@ -94292,7 +97266,7 @@ var ts; } } function getCallSignatureDefinition() { - return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) : undefined; } @@ -94330,7 +97304,7 @@ var ts; return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); } function findReferenceInPosition(refs, pos) { - return ts.find(refs, function (ref) { return ref.pos <= pos && pos <= ref.end; }); + return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); } GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { @@ -94366,48 +97340,83 @@ var ts; var JsDoc; (function (JsDoc) { var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", "augments", "author", - "argument", "borrows", "callback", "class", + "classdesc", "constant", "constructor", "constructs", + "copyright", "default", "deprecated", "description", + "emits", + "enum", "event", "example", + "exports", "extends", + "external", "field", - "fileOverview", + "file", + "fileoverview", + "fires", "function", + "generator", + "global", + "hideconstructor", + "host", "ignore", - "inheritDoc", + "implements", + "inheritdoc", "inner", + "instance", + "interface", + "kind", "lends", - "link", - "memberOf", + "license", + "listens", + "member", + "memberof", "method", + "mixes", + "module", "name", "namespace", + "override", + "package", "param", "private", - "prop", "property", + "protected", "public", + "readonly", "requires", "returns", "see", "since", "static", + "summary", "template", + "this", "throws", + "todo", + "tutorial", "type", "typedef", - "version" + "var", + "variation", + "version", + "virtual", + "yields" ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; @@ -94435,11 +97444,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 293 /* JSDocParameterTag */: - case 298 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: return [declaration]; - case 292 /* JSDocCallbackTag */: - case 297 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -94460,16 +97469,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 290 /* JSDocAugmentsTag */: + case 293 /* JSDocAugmentsTag */: return withNode(tag.class); - case 296 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 295 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 297 /* JSDocTypedefTag */: - case 292 /* JSDocCallbackTag */: - case 298 /* JSDocPropertyTag */: - case 293 /* JSDocParameterTag */: + case 302 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -94595,13 +97604,15 @@ var ts; * be performed. */ function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { - // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); + if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { + // Non-empty comment already exists. return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var tokenStart = tokenAtPos.getStart(sourceFile); - if (!tokenAtPos || tokenStart < position) { + // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.) + if (!existingDocComment && tokenStart < position) { return undefined; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); @@ -94617,10 +97628,7 @@ var ts; var singleLineResult = "/** */"; return { newText: singleLineResult, caretOffset: 3 }; } - 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 indentationStr = getIndentationStringAtPosition(sourceFile, position); // A doc comment consists of the following // * The opening comment line // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) @@ -94628,8 +97636,7 @@ var ts; // * TODO: other tags. // * the closing comment line // * if the caret was directly in front of the object, then we add an extra line and indentation. - var preamble = "/**" + newLine + - indentationStr + " * "; + var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + @@ -94637,6 +97644,14 @@ var ts; return { newText: result, caretOffset: preamble.length }; } JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getIndentationStringAtPosition(sourceFile, position) { + var text = sourceFile.text; + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + var pos = lineStart; + for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) + ; + return text.slice(lineStart, pos); + } function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { return parameters.map(function (_a, i) { var name = _a.name, dotDotDotToken = _a.dotDotDotToken; @@ -94646,44 +97661,48 @@ var ts; }).join(""); } function getCommentOwnerInfo(tokenAtPos) { - for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 234 /* FunctionDeclaration */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 153 /* MethodSignature */: - var parameters = commentOwner.parameters; - return { commentOwner: commentOwner, parameters: parameters }; - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 151 /* PropertySignature */: - case 238 /* EnumDeclaration */: - case 273 /* EnumMember */: - case 237 /* TypeAliasDeclaration */: - return { commentOwner: commentOwner }; - case 214 /* 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 274 /* SourceFile */: - return undefined; - case 239 /* 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 === 239 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 200 /* 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.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + } + function getCommentOwnerInfoWorker(commentOwner) { + switch (commentOwner.kind) { + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 153 /* MethodSignature */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 273 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer); + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 151 /* PropertySignature */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 240 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; + case 217 /* 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 277 /* SourceFile */: + return "quit"; + case 242 /* 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 === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 202 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + return "quit"; } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; } } } @@ -94696,14 +97715,14 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 191 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 193 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return rightHandSide.parameters; - case 205 /* ClassExpression */: { + case 207 /* ClassExpression */: { var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); return ctr ? ctr.parameters : ts.emptyArray; } @@ -94722,9 +97741,9 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_4 = function (sourceFile) { + var _loop_14 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { + if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; } sourceFile.getNamedDeclarations().forEach(function (declarations, name) { @@ -94732,15 +97751,12 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - _loop_4(sourceFile); + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; + _loop_14(sourceFile); } rawItems.sort(compareNavigateToItems); - if (maxResultCount !== undefined) { - rawItems = rawItems.slice(0, maxResultCount); - } - return rawItems.map(createNavigateToItem); + return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); } NavigateTo.getNavigateToItems = getNavigateToItems; function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { @@ -94750,28 +97766,28 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { - var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); // TODO: GH#18217 + // If the pattern has dots in it, then also see if the declaration container matches as well. + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); if (fullMatch) { rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); } } else { - // If the pattern has dots in it, then also see if the declaration container matches as well. rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration }); } } } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 245 /* ImportClause */: - case 248 /* ImportSpecifier */: - case 243 /* ImportEqualsDeclaration */: - var importer = checker.getSymbolAtLocation(declaration.name); + case 248 /* ImportClause */: + case 251 /* ImportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; default: @@ -94780,54 +97796,37 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - if (name && ts.isPropertyNameLiteral(name)) { - containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); - return true; - } - else if (name && name.kind === 147 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; - } + return !!name && (pushLiteral(name, containers) || name.kind === 147 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // // [X.Y.Z]() { } - function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - if (ts.isPropertyNameLiteral(expression)) { - var text = ts.getTextOfIdentifierOrLiteral(expression); - if (includeLastPortion) { - containers.unshift(text); - } - return true; - } - if (ts.isPropertyAccessExpression(expression)) { - if (includeLastPortion) { - containers.unshift(expression.name.text); - } - return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true); - } - return false; + function tryAddComputedPropertyName(expression, containers) { + return pushLiteral(expression, containers) + || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers); + } + function pushLiteral(node, containers) { + return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true); } 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 === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { - return undefined; + if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + return ts.emptyArray; } + // Don't include the last portion. + containers.shift(); // Now, walk up our containers, adding all their names to the container array. var container = ts.getContainerNode(declaration); while (container) { if (!tryAddSingleDeclarationName(container, containers)) { - return undefined; + return ts.emptyArray; } container = ts.getContainerNode(container); } - return containers; + return containers.reverse(); } function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. @@ -94848,7 +97847,7 @@ var ts; 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 */ // TODO: GH#18217 Just use `container ? ...` + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, }; } })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); @@ -94966,7 +97965,7 @@ var ts; /** Call after calling `startNode` and adding children to it. */ function endNode() { if (parent.children) { - mergeChildren(parent.children); + mergeChildren(parent.children, parent); sortChildren(parent.children); } parent = parentsStack.pop(); @@ -95009,19 +98008,19 @@ var ts; addLeafNode(node); } break; - case 245 /* ImportClause */: + case 248 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; if (importClause.name) { - addLeafNode(importClause); + addLeafNode(importClause.name); } // Handle named bindings in imports e.g.: // import * as NS from "mod"; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 246 /* NamespaceImport */) { + if (namedBindings.kind === 249 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -95032,8 +98031,8 @@ var ts; } } break; - case 182 /* BindingElement */: - case 232 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 235 /* VariableDeclaration */: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -95054,12 +98053,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 193 /* ArrowFunction */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -95069,9 +98068,9 @@ var ts; } endNode(); break; - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 236 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -95079,18 +98078,18 @@ var ts; } endNode(); break; - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 252 /* ExportSpecifier */: - case 243 /* ImportEqualsDeclaration */: + case 255 /* ExportSpecifier */: + case 246 /* ImportEqualsDeclaration */: case 160 /* IndexSignature */: case 158 /* CallSignature */: case 159 /* ConstructSignature */: - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 200 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var special = ts.getSpecialPropertyAssignmentKind(node); switch (special) { case 1 /* ExportsProperty */: @@ -95098,7 +98097,7 @@ var ts; case 3 /* PrototypeProperty */: case 6 /* Prototype */: addNodeWithRecursiveChild(node, node.right); - break; + return; case 4 /* ThisProperty */: case 5 /* Property */: case 0 /* None */: @@ -95122,7 +98121,7 @@ var ts; } } /** Merge declarations of the same kind. */ - function mergeChildren(children) { + function mergeChildren(children, node) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var declName = ts.getNameOfDeclaration(child.node); @@ -95139,7 +98138,7 @@ var ts; if (itemsWithSameName instanceof Array) { for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { var itemWithSameName = itemsWithSameName_1[_i]; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } } @@ -95148,7 +98147,7 @@ var ts; } else { var itemWithSameName = itemsWithSameName; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } nameToItems.set(name, [itemWithSameName, child]); @@ -95156,16 +98155,16 @@ var ts; } }); } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { merge(a, b); return true; } return false; } /** a and b have the same name, but they may not be mergeable. */ - function shouldReallyMerge(a, b) { - if (a.kind !== b.kind) { + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { return false; } switch (a.kind) { @@ -95174,17 +98173,23 @@ var ts; case 156 /* GetAccessor */: case 157 /* SetAccessor */: return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return areSameModule(a, b); default: return true; } } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { // TODO: GH#18217 - return a.body.kind === b.body.kind && (a.body.kind !== 239 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 242 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -95196,7 +98201,7 @@ var ts; } target.children = ts.concatenate(target.children, source.children); if (target.children) { - mergeChildren(target.children); + mergeChildren(target.children, target); sortChildren(target.children); } } @@ -95214,24 +98219,24 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 239 /* ModuleDeclaration */) { + if (node.kind === 242 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); - if (declName) { + if (declName && ts.isPropertyName(declName)) { return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: - case 205 /* ClassExpression */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 207 /* ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 239 /* ModuleDeclaration */) { + if (node.kind === 242 /* ModuleDeclaration */) { return getModuleName(node); } if (name) { @@ -95241,16 +98246,16 @@ var ts; } } switch (node.kind) { - case 274 /* SourceFile */: + case 277 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 193 /* ArrowFunction */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -95288,25 +98293,25 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 238 /* EnumDeclaration */: - case 236 /* InterfaceDeclaration */: - case 239 /* ModuleDeclaration */: - case 274 /* SourceFile */: - case 237 /* TypeAliasDeclaration */: - case 297 /* JSDocTypedefTag */: - case 292 /* JSDocCallbackTag */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 241 /* EnumDeclaration */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 277 /* SourceFile */: + case 240 /* TypeAliasDeclaration */: + case 302 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: return true; case 155 /* Constructor */: case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 193 /* ArrowFunction */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -95316,8 +98321,8 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 240 /* ModuleBlock */: - case 274 /* SourceFile */: + case 243 /* ModuleBlock */: + case 277 /* SourceFile */: case 154 /* MethodDeclaration */: case 155 /* Constructor */: return true; @@ -95328,7 +98333,7 @@ var ts; function hasSomeImportantChild(item) { return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 232 /* VariableDeclaration */ && childKind !== 182 /* BindingElement */; + return childKind !== 235 /* VariableDeclaration */ && childKind !== 184 /* BindingElement */; }); } } @@ -95385,7 +98390,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 239 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -95396,16 +98401,16 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 239 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217 + return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { return !member.name || member.name.kind === 147 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 274 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 277 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 232 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 235 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -95415,16 +98420,16 @@ var ts; return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 232 /* VariableDeclaration */) { + else if (node.parent.kind === 235 /* VariableDeclaration */) { return ts.declarationNameToString(node.parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 200 /* BinaryExpression */ && + else if (node.parent.kind === 202 /* BinaryExpression */ && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 270 /* PropertyAssignment */ && node.parent.name) { + else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } // Default exports are named "default" @@ -95437,9 +98442,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 193 /* ArrowFunction */: - case 192 /* FunctionExpression */: - case 205 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 207 /* ClassExpression */: return true; default: return false; @@ -95495,10 +98500,7 @@ var ts; }); // Delete or replace the first import. if (newImportDecls.length === 0) { - changeTracker.deleteNode(sourceFile, oldImportDecls[0], { - useNonAdjustedStartPosition: true, - useNonAdjustedEndPosition: false, - }); + changeTracker.delete(sourceFile, oldImportDecls[0]); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. @@ -95510,7 +98512,7 @@ var ts; } // Delete any subsequent imports. for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + changeTracker.delete(sourceFile, oldImportDecls[i]); } } } @@ -95806,7 +98808,7 @@ var ts; var currentLineStart = lineStarts[i]; var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; var lineText = sourceFile.text.substring(currentLineStart, lineEnd); - var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/); + var result = isRegionDelimiter(lineText); if (!result || ts.isInComment(sourceFile, currentLineStart)) { continue; } @@ -95824,6 +98826,10 @@ var ts; } } } + var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/; + function isRegionDelimiter(lineText) { + return regionDelimiterRegExp.exec(lineText); + } function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); if (!comments) @@ -95831,11 +98837,19 @@ var ts; var firstSingleLineCommentStart = -1; var lastSingleLineCommentEnd = -1; var singleLineCommentCount = 0; - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + var sourceText = sourceFile.getFullText(); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end; cancellationToken.throwIfCancellationRequested(); switch (kind) { case 2 /* SingleLineCommentTrivia */: + // never fold region delimiters into single-line comment regions + var commentText = sourceText.slice(pos, end); + if (isRegionDelimiter(commentText)) { + combineAndAddMultipleSingleLineComments(); + singleLineCommentCount = 0; + break; + } // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last if (singleLineCommentCount === 0) { @@ -95866,24 +98880,24 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 213 /* Block */: + case 216 /* Block */: if (ts.isFunctionBlock(n)) { - return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 193 /* ArrowFunction */); + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 195 /* ArrowFunction */); } // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 218 /* DoStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 220 /* ForStatement */: - case 217 /* IfStatement */: - case 219 /* WhileStatement */: - case 226 /* WithStatement */: - case 269 /* CatchClause */: + case 221 /* DoStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 223 /* ForStatement */: + case 220 /* IfStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: + case 272 /* CatchClause */: return spanForNode(n.parent); - case 230 /* TryStatement */: + case 233 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { @@ -95898,17 +98912,34 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: return spanForNode(n.parent); - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: - case 238 /* EnumDeclaration */: - case 241 /* CaseBlock */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 244 /* CaseBlock */: return spanForNode(n); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); + case 258 /* JsxElement */: + return spanForJSXElement(n); + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 17 /* OpenBraceToken */; } @@ -95981,7 +99012,6 @@ var ts; if (!candidateMatch) { return undefined; } - candidateContainers = candidateContainers || []; // -1 because the last part was checked against the name, and only the rest // of the parts are checked against the container. if (dotSeparatedSegments.length - 1 > candidateContainers.length) { @@ -96218,15 +99248,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_5 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_1 = _loop_5(start); - if (typeof state_1 === "object") - return state_1.value; + var state_3 = _loop_15(start); + if (typeof state_3 === "object") + return state_3.value; } return -1; } @@ -96740,21 +99770,12 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) { - var getCanonicalDefaultLibName = ts.memoize(function () { return getCanonicalFileName(ts.normalizePath(defaultLibFileName)); }); + function getRenameInfo(program, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); var renameInfo = node && nodeIsEligibleForRename(node) - ? getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) : undefined; return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); - function isDefinedInLibraryFile(declaration) { - if (!defaultLibFileName) { - return false; - } - var sourceFile = declaration.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName)); - return canonicalName === getCanonicalDefaultLibName(); - } } Rename.getRenameInfo = getRenameInfo; function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { @@ -96777,7 +99798,7 @@ var ts; if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 147 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); @@ -96836,19 +99857,13 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - var ArgumentListKind; - (function (ArgumentListKind) { - ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; - ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; - ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; - ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind || (ArgumentListKind = {})); var InvocationKind; (function (InvocationKind) { InvocationKind[InvocationKind["Call"] = 0] = "Call"; InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual"; })(InvocationKind || (InvocationKind = {})); - function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { + function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { var typeChecker = program.getTypeChecker(); // Decide whether to show signature help var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); @@ -96856,83 +99871,124 @@ var ts; // We are at the beginning of the file return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); + // Only need to be careful if the user typed a character and signature help wasn't showing. + var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { + return undefined; + } + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); - // Semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - if (ts.isSourceFileJavaScript(sourceFile)) { - return createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken); - } - return undefined; + return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(argumentInfo, checker) { - var invocation = argumentInfo.invocation; - if (invocation.kind === 0 /* Call */) { - var candidates = []; - var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = _a.invocation, argumentCount = _a.argumentCount; + switch (invocation.kind) { + case 0 /* Call */: { + if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { + return undefined; + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + } + case 1 /* TypeArgs */: { + if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + case 2 /* Contextual */: + return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + default: + return ts.Debug.assertNever(invocation); } - else { - var type = checker.getTypeAtLocation(invocation.called); // TODO: GH#18217 - var signatures = ts.isNewExpression(invocation.called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); - var candidates = signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= argumentInfo.argumentCount; }); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + function isSyntacticOwner(startingToken, node, sourceFile) { + if (!ts.isCallOrNewExpression(node)) + return false; + var invocationChildren = node.getChildren(sourceFile); + switch (startingToken.kind) { + case 19 /* OpenParenToken */: + return ts.contains(invocationChildren, startingToken); + case 26 /* CommaToken */: { + var containingList = ts.findContainingList(startingToken); + return !!containingList && ts.contains(invocationChildren, containingList); + } + case 27 /* LessThanToken */: + return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + default: + return false; } } function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + if (argumentInfo.invocation.kind === 2 /* Contextual */) + return undefined; // See if we can find some symbol with the call expression name that has call signatures. var expression = getExpressionFromInvocation(argumentInfo.invocation); - var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; - if (!name || !name.escapedText) { - return undefined; - } + var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined; var typeChecker = program.getTypeChecker(); - var _loop_6 = function (sourceFile) { - var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = nameToDeclarations.get(name.text); - if (declarations) { - var _loop_7 = function (declaration) { - var symbol = declaration.symbol; - if (symbol) { - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); - if (type) { - var callSignatures_1 = type.getCallSignatures(); - if (callSignatures_1 && callSignatures_1.length) { - return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; - } - } - } - }; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; - var state_3 = _loop_7(declaration); - if (typeof state_3 === "object") - return state_3; + return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) { + return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) { + var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration); + var callSignatures = type && type.getCallSignatures(); + if (callSignatures && callSignatures.length) { + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); }); } - } - }; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - var state_2 = _loop_6(sourceFile); - if (typeof state_2 === "object") - return state_2.value; - } + }); + }); + } + function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(calledExpression, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); - return !info || info.kind === 0 /* TypeArguments */ || info.invocation.kind === 1 /* TypeArgs */ ? undefined + return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; } SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; + function getArgumentOrParameterListInfo(node, sourceFile) { + var info = getArgumentOrParameterListAndIndex(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex; + var argumentCount = getArgumentCount(list); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + } + function getArgumentOrParameterListAndIndex(node, sourceFile) { + if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. + return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; + } + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + var list = ts.findContainingList(node); + return list && { list: list, argumentIndex: getArgumentIndex(list, node) }; + } + } /** * Returns relevant information for the argument list and the current argument if we are * in the argument of an invocation; returns undefined otherwise. @@ -96941,8 +99997,6 @@ var ts; var parent = node.parent; if (ts.isCallOrNewExpression(parent)) { var invocation = parent; - var list = void 0; - var argumentIndex = void 0; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a signature help session // 2. The token is either not associated with a list, or ends a list, so the session should end @@ -96957,32 +100011,12 @@ var ts; // Case 3: // foo(a#, #b#) -> The token is buried inside a list, and should give signature help // Find out if 'node' is an argument, a type argument, or neither - if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { - // Find the list that starts right *after* the < or ( token. - // If the user has just opened a list, consider this item 0. - list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); - ts.Debug.assert(list !== undefined); - argumentIndex = 0; - } - else { - // findListItemInfo can return undefined if we are not in parent's argument list - // or type argument list. This includes cases where the cursor is: - // - To the right of the closing parenthesis, non-substitution template, or template tail. - // - Between the type arguments and the arguments (greater than token) - // - On the target of the call (parent.func) - // - On the 'new' keyword in a 'new' expression - list = ts.findContainingList(node); - if (!list) - return undefined; - argumentIndex = getArgumentIndex(list, node); - } - var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; - var argumentCount = getArgumentCount(list); - if (argumentIndex !== 0) { - ts.Debug.assertLessThan(argumentIndex, argumentCount); - } - var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var info = getArgumentOrParameterListInfo(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos; + return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { // Check if we're actually inside the template; @@ -96990,11 +100024,12 @@ var ts; if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); } + return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 189 /* TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 202 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 204 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -97018,7 +100053,7 @@ var ts; var attributeSpanStart = parent.attributes.pos; var attributeSpanEnd = ts.skipTrivia(sourceFile.text, parent.attributes.end, /*stopAfterLineBreak*/ false); return { - kind: 3 /* JSXAttributesArguments */, + isTypeParameterList: false, invocation: { kind: 0 /* Call */, node: parent }, argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart), argumentIndex: 0, @@ -97026,15 +100061,67 @@ var ts; }; } else { - var typeArgInfo = ts.isPossiblyTypeArgumentPosition(node, sourceFile); + var typeArgInfo = ts.getPossibleTypeArgumentsInfo(node, sourceFile); if (typeArgInfo) { var called = typeArgInfo.called, nTypeArguments = typeArgInfo.nTypeArguments; var invocation = { kind: 1 /* TypeArgs */, called: called }; var argumentsSpan = ts.createTextSpanFromBounds(called.getStart(sourceFile), node.end); - return { kind: 0 /* TypeArguments */, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; + return { isTypeParameterList: true, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; } + return undefined; } - return undefined; + } + function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) { + return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile); + } + function getHighestBinary(b) { + return ts.isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b; + } + function countBinaryExpressionParameters(b) { + return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2; + } + function tryGetParameterInfo(startingToken, _position, sourceFile, checker) { + var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker); + if (!info) + return undefined; + var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var signatures = contextualType.getCallSignatures(); + if (signatures.length !== 1) + return undefined; + var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(contextualType.symbol) }; + return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { + if (startingToken.kind !== 19 /* OpenParenToken */ && startingToken.kind !== 26 /* CommaToken */) + return undefined; + var parent = startingToken.parent; + switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + case 154 /* MethodDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + var info = getArgumentOrParameterListInfo(startingToken, sourceFile); + if (!info) + return undefined; + var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); + return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + case 202 /* BinaryExpression */: { + var highestBinary = getHighestBinary(parent); + var contextualType_1 = checker.getContextualType(highestBinary); + var argumentIndex_1 = startingToken.kind === 19 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; + var argumentCount_1 = countBinaryExpressionParameters(highestBinary); + return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) }; + } + default: + return undefined; + } + } + // The type of a function type node has a symbol at that node, but it's better to use the symbol for a parameter or type alias. + function chooseBetterSymbol(s) { + return s.name === "__type" /* Type */ + ? ts.firstDefined(s.declarations, function (d) { return ts.isFunctionTypeNode(d) ? d.parent.symbol : undefined; }) || s + : s; } function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may @@ -97111,7 +100198,7 @@ var ts; ts.Debug.assertLessThan(argumentIndex, argumentCount); } return { - kind: 2 /* TaggedTemplateArguments */, + isTypeParameterList: false, invocation: { kind: 0 /* Call */, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, @@ -97143,7 +100230,7 @@ var ts; // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 202 /* TemplateExpression */) { + if (template.kind === 204 /* TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -97151,18 +100238,18 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile) { - var _loop_8 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker) { + var _loop_16 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); - var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); + var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker); if (argumentInfo) { return { value: argumentInfo }; } }; for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_8(n); + var state_4 = _loop_16(n); if (typeof state_4 === "object") return state_4.value; } @@ -97177,102 +100264,195 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } - var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { - var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; - var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.called; - var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); - var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); - var printer = ts.createPrinter({ removeComments: true }); - var items = candidates.map(function (candidateSignature) { - var signatureHelpParameters; - var prefixDisplayParts = []; - var suffixDisplayParts = []; - if (callTargetDisplayParts) { - ts.addRange(prefixDisplayParts, callTargetDisplayParts); - } - var isVariadic; - if (isTypeParameterList) { - isVariadic = false; // type parameter lists are not variadic - prefixDisplayParts.push(ts.punctuationPart(27 /* LessThanToken */)); - 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) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); - }); - ts.addRange(suffixDisplayParts, parameterParts); - } - else { - isVariadic = candidateSignature.hasRestParameter; - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); - printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); - } - }); - ts.addRange(prefixDisplayParts, typeParameterParts); - prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - signatureHelpParameters = ts.map(candidateSignature.parameters, createSignatureHelpParameterForParameter); - suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); - } - var returnTypeParts = ts.mapToDisplayParts(function (writer) { - writer.writePunctuation(":"); - writer.writeSpace(" "); - var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); - if (predicate) { - typeChecker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); - } - else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); - } - }); - ts.addRange(suffixDisplayParts, returnTypeParts); - return { - isVariadic: isVariadic, - prefixDisplayParts: prefixDisplayParts, - suffixDisplayParts: suffixDisplayParts, - separatorDisplayParts: [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()], - parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment(typeChecker), - tags: candidateSignature.getJsDocTags() - }; - }); + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { + var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); + var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; + var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var selectedItemIndex = candidates.indexOf(resolvedSignature); ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; - function createSignatureHelpParameterForParameter(parameter) { - var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); - printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); - }); - return { - name: parameter.name, - documentation: parameter.getDocumentationComment(typeChecker), - displayParts: displayParts, - isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) - }; + } + function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { + var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; + var prefixDisplayParts = callTargetDisplayParts.concat(prefix); + var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; + var documentation = candidateSignature.getDocumentationComment(checker); + var tags = candidateSignature.getJsDocTags(); + return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) { + return ts.mapToDisplayParts(function (writer) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = checker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); + } + else { + checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); + } + }); + } + function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; + var printer = ts.createPrinter({ removeComments: true }); + var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var parameterParts = ts.mapToDisplayParts(function (writer) { + var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); + }); + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(27 /* LessThanToken */)], suffix: [ts.punctuationPart(29 /* GreaterThanToken */)].concat(parameterParts) }; + } + function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var isVariadic = candidateSignature.hasRestParameter; + var printer = ts.createPrinter({ removeComments: true }); + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); + } + }); + var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(19 /* OpenParenToken */)]), suffix: [ts.punctuationPart(20 /* CloseParenToken */)] }; + } + function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + } + function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + } + })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + var sourcemappedFileCache; + return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; } - function createSignatureHelpParameterForTypeParameter(typeParameter) { - var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); - }); - return { - name: typeParameter.symbol.name, - documentation: ts.emptyArray, - displayParts: displayParts, - isOptional: false - }; + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); + var comment = sourceMapCommentRegExp.exec(lineText); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!lineText.match(whitespaceOrMapCommentRegExp)) { + break; + } } } - })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + // swallow error + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + // obviously invalid map + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, getProgram(), sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function tryGetOriginalLocation(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); + return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + } + function tryGetGeneratedLocation(info) { + var program = getProgram(); + var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = ts.createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; })(ts || (ts = {})); /* @internal */ var ts; @@ -97280,6 +100460,7 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; + var checker = program.getDiagnosticsProducingTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { @@ -97294,8 +100475,8 @@ var ts; var name = importNameForConvertToDefaultImport(importNode); if (!name) continue; - var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); } @@ -97307,7 +100488,7 @@ var ts; function check(node) { if (isJsFile) { switch (node.kind) { - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: var decl = ts.getDeclarationOfJSInitializer(node); if (decl) { var symbol_2 = decl.symbol; @@ -97317,7 +100498,7 @@ var ts; } } // falls through if no diagnostic was created - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: var symbol = node.symbol; if (symbol.members && (symbol.members.size > 0)) { diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); @@ -97339,6 +100520,9 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } + if (ts.isFunctionLikeDeclaration(node)) { + addConvertToAsyncFunctionDiagnostics(node, checker, diags); + } node.forEachChild(check); } } @@ -97347,11 +100531,11 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); }); // TODO: GH#18217 - case 216 /* ExpressionStatement */: { + case 219 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); @@ -97368,20 +100552,67 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 246 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 249 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return node.name; default: return undefined; } } + function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { + var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; + if (ts.isAsyncFunction(node) || !node.body || !functionType) { + return; + } + var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); + var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { + return; + } + // collect all the return statements + // check that a property access expression exists in there and that it is a handler + var returnStatements = getReturnStatementsWithPromiseHandlers(node); + if (returnStatements.length > 0) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } + /** @internal */ + function getReturnStatementsWithPromiseHandlers(node) { + var returnStatements = []; + if (ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + else { + visit(node); + } + function visit(child) { + if (ts.isFunctionLike(child)) { + return; + } + if (ts.isReturnStatement(child)) { + ts.forEachChild(child, addHandlers); + } + function addHandlers(returnChild) { + if (isPromiseHandler(returnChild)) { + returnStatements.push(child); + } + } + ts.forEachChild(child, visit); + } + return returnStatements; + } + ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + function isPromiseHandler(node) { + return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && + (node.expression.name.text === "then" || node.expression.name.text === "catch")); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -97396,7 +100627,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 205 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -97441,7 +100672,7 @@ var ts; if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { return "parameter" /* parameterElement */; } - else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { + else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) { return "const" /* constElement */; } else if (ts.forEach(symbol.declarations, ts.isLet)) { @@ -97484,11 +100715,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 257 /* JsxOpeningElement */: - case 255 /* JsxElement */: - case 256 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 262 /* JsxAttribute */: + case 265 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -97528,7 +100759,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 185 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 187 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -97549,7 +100780,7 @@ var ts; if (callExpressionLike) { var candidateSignatures = []; signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 188 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 190 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -97636,7 +100867,7 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 205 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -97670,7 +100901,7 @@ var ts; } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); - if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { + if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } @@ -97680,7 +100911,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 239 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 242 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 130 /* NamespaceKeyword */ : 129 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -97718,7 +100949,7 @@ var ts; } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 237 /* TypeAliasDeclaration */) { + else if (declaration.kind === 240 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path @@ -97735,7 +100966,7 @@ var ts; symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 273 /* EnumMember */) { + if (declaration.kind === 276 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -97765,17 +100996,17 @@ var ts; } } switch (symbol.declarations[0].kind) { - case 242 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(130 /* NamespaceKeyword */)); break; - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); break; - case 252 /* ExportSpecifier */: + case 255 /* ExportSpecifier */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); break; default: @@ -97784,7 +101015,7 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 243 /* ImportEqualsDeclaration */) { + if (declaration.kind === 246 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -97862,10 +101093,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 274 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 277 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 200 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 202 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -97977,16 +101208,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 192 /* FunctionExpression */) { + if (declaration.kind === 194 /* FunctionExpression */) { return true; } - if (declaration.kind !== 232 /* VariableDeclaration */ && declaration.kind !== 234 /* FunctionDeclaration */) { + if (declaration.kind !== 235 /* VariableDeclaration */ && declaration.kind !== 237 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 274 /* SourceFile */ || parent.kind === 240 /* ModuleBlock */) { + if (parent.kind === 277 /* SourceFile */ || parent.kind === 243 /* ModuleBlock */) { return false; } } @@ -98099,7 +101330,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -98118,7 +101349,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_17(opt); } return options; } @@ -98295,10 +101526,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 262 /* JsxAttribute */: - case 257 /* JsxOpeningElement */: - case 258 /* JsxClosingElement */: - case 256 /* JsxSelfClosingElement */: + case 265 /* JsxAttribute */: + case 260 /* JsxOpeningElement */: + case 261 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: // 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 */; } @@ -98779,44 +102010,44 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 220 /* ForStatement */; + return context.contextNode.kind === 223 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 200 /* BinaryExpression */: - case 201 /* ConditionalExpression */: - case 171 /* ConditionalType */: - case 208 /* AsExpression */: - case 252 /* ExportSpecifier */: - case 248 /* ImportSpecifier */: + case 202 /* BinaryExpression */: + case 203 /* ConditionalExpression */: + case 173 /* ConditionalType */: + case 210 /* AsExpression */: + case 255 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: case 161 /* TypePredicate */: - case 169 /* UnionType */: - case 170 /* IntersectionType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 182 /* BindingElement */: + case 184 /* BindingElement */: // equals in type X = ... - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: // equal in p = 0; case 149 /* Parameter */: - case 273 /* EnumMember */: + case 276 /* EnumMember */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] case 148 /* TypeParameter */: return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: return context.currentTokenSpan.kind === 145 /* OfKeyword */ || context.nextTokenSpan.kind === 145 /* OfKeyword */; } return false; @@ -98832,19 +102063,19 @@ var ts; return contextKind === 152 /* PropertyDeclaration */ || contextKind === 151 /* PropertySignature */ || contextKind === 149 /* Parameter */ || - contextKind === 232 /* VariableDeclaration */ || + contextKind === 235 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 201 /* ConditionalExpression */ || - context.contextNode.kind === 171 /* ConditionalType */; + return context.contextNode.kind === 203 /* ConditionalExpression */ || + context.contextNode.kind === 173 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 180 /* ObjectBindingPattern */ || - context.contextNode.kind === 177 /* MappedType */ || + return context.contextNode.kind === 182 /* ObjectBindingPattern */ || + context.contextNode.kind === 179 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -98870,17 +102101,17 @@ var ts; return true; } switch (node.kind) { - case 213 /* Block */: - case 241 /* CaseBlock */: - case 184 /* ObjectLiteralExpression */: - case 240 /* ModuleBlock */: + case 216 /* Block */: + case 244 /* CaseBlock */: + case 186 /* ObjectLiteralExpression */: + case 243 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: @@ -98888,13 +102119,13 @@ var ts; case 157 /* SetAccessor */: // case SyntaxKind.MethodSignature: case 158 /* CallSignature */: - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: case 155 /* Constructor */: - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 236 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 239 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -98903,40 +102134,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 234 /* FunctionDeclaration */ || context.contextNode.kind === 192 /* FunctionExpression */; + return context.contextNode.kind === 237 /* FunctionDeclaration */ || context.contextNode.kind === 194 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 236 /* InterfaceDeclaration */: - case 238 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: case 166 /* TypeLiteral */: - case 239 /* ModuleDeclaration */: - case 250 /* ExportDeclaration */: - case 251 /* NamedExports */: - case 244 /* ImportDeclaration */: - case 247 /* NamedImports */: + case 242 /* ModuleDeclaration */: + case 253 /* ExportDeclaration */: + case 254 /* NamedExports */: + case 247 /* ImportDeclaration */: + case 250 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 235 /* ClassDeclaration */: - case 239 /* ModuleDeclaration */: - case 238 /* EnumDeclaration */: - case 269 /* CatchClause */: - case 240 /* ModuleBlock */: - case 227 /* SwitchStatement */: + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 272 /* CatchClause */: + case 243 /* ModuleBlock */: + case 230 /* SwitchStatement */: return true; - case 213 /* Block */: { + case 216 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 193 /* ArrowFunction */ && blockParent.kind !== 192 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 195 /* ArrowFunction */ && blockParent.kind !== 194 /* FunctionExpression */) { return true; } } @@ -98945,31 +102176,31 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 217 /* IfStatement */: - case 227 /* SwitchStatement */: - case 220 /* ForStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 219 /* WhileStatement */: - case 230 /* TryStatement */: - case 218 /* DoStatement */: - case 226 /* WithStatement */: + case 220 /* IfStatement */: + case 230 /* SwitchStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 222 /* WhileStatement */: + case 233 /* TryStatement */: + case 221 /* DoStatement */: + case 229 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 269 /* CatchClause */: + case 272 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 184 /* ObjectLiteralExpression */; + return context.contextNode.kind === 186 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 187 /* CallExpression */; + return context.contextNode.kind === 189 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 188 /* NewExpression */; + return context.contextNode.kind === 190 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); @@ -98981,28 +102212,28 @@ var ts; return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 193 /* ArrowFunction */; + return context.contextNode.kind === 195 /* ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 179 /* ImportType */; + return context.contextNode.kind === 181 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 255 /* JsxElement */ && context.contextNode.kind !== 259 /* JsxFragment */; + return context.contextNode.kind !== 258 /* JsxElement */ && context.contextNode.kind !== 262 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 265 /* JsxExpression */ || context.contextNode.kind === 264 /* JsxSpreadAttribute */; + return context.contextNode.kind === 268 /* JsxExpression */ || context.contextNode.kind === 267 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 262 /* JsxAttribute */; + return context.nextTokenParent.kind === 265 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 262 /* JsxAttribute */; + return context.contextNode.kind === 265 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 256 /* JsxSelfClosingElement */; + return context.contextNode.kind === 259 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -99020,14 +102251,14 @@ var ts; return node.kind === 150 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 233 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 236 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 239 /* ModuleDeclaration */; + return context.contextNode.kind === 242 /* ModuleDeclaration */; } function isObjectTypeContext(context) { return context.contextNode.kind === 166 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; @@ -99041,21 +102272,21 @@ var ts; } switch (parent.kind) { case 162 /* TypeReference */: - case 190 /* TypeAssertionExpression */: - case 237 /* TypeAliasDeclaration */: - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 236 /* InterfaceDeclaration */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 192 /* TypeAssertionExpression */: + case 240 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 158 /* CallSignature */: case 159 /* ConstructSignature */: - case 187 /* CallExpression */: - case 188 /* NewExpression */: - case 207 /* ExpressionWithTypeArguments */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 209 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -99066,16 +102297,16 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 190 /* TypeAssertionExpression */; + return context.contextNode.kind === 192 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 196 /* VoidExpression */; + return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 198 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 203 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 205 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 209 /* NonNullExpression */; + return context.contextNode.kind === 211 /* NonNullExpression */; } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -99309,17 +102540,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 235 /* ClassDeclaration */: - case 236 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 240 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 274 /* SourceFile */: - case 213 /* Block */: - case 240 /* ModuleBlock */: + return !!body && body.kind === 243 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 277 /* SourceFile */: + case 216 /* Block */: + case 243 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -99542,10 +102773,10 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 235 /* ClassDeclaration */: return 75 /* ClassKeyword */; - case 236 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; - case 234 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; - case 238 /* EnumDeclaration */: return 238 /* EnumDeclaration */; + case 238 /* ClassDeclaration */: return 75 /* ClassKeyword */; + case 239 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; + case 237 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; + case 241 /* EnumDeclaration */: return 241 /* EnumDeclaration */; case 156 /* GetAccessor */: return 125 /* GetKeyword */; case 157 /* SetAccessor */: return 136 /* SetKeyword */; case 154 /* MethodDeclaration */: @@ -99555,7 +102786,10 @@ var ts; // falls through case 152 /* PropertyDeclaration */: case 149 /* Parameter */: - return ts.getNameOfDeclaration(node).kind; + var name = ts.getNameOfDeclaration(node); + if (name) { + return name.kind; + } } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -99599,15 +102833,15 @@ var ts; case 41 /* SlashToken */: case 29 /* GreaterThanToken */: switch (container.kind) { - case 257 /* JsxOpeningElement */: - case 258 /* JsxClosingElement */: - case 256 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 261 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: return false; } break; case 21 /* OpenBracketToken */: case 22 /* CloseBracketToken */: - if (container.kind !== 177 /* MappedType */) { + if (container.kind !== 179 /* MappedType */) { return false; } break; @@ -99707,7 +102941,7 @@ var ts; indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); } childContextNode = node; - if (isFirstListItem && parent.kind === 183 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 185 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -99715,7 +102949,6 @@ var ts; function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); - var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { @@ -99729,8 +102962,8 @@ var ts; else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); + var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } else { @@ -99744,17 +102977,20 @@ var ts; var child = nodes[i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } - if (listEndToken !== 0 /* Unknown */) { - if (formattingScanner.isOnToken()) { - var tokenInfo = formattingScanner.readTokenInfo(parent); - // consume the list end token only if it is still belong to the parent - // there might be the case when current token matches end token but does not considered as one - // function (x: function) <-- - // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { - // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); - } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.readTokenInfo(parent); + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } } } @@ -99930,7 +103166,6 @@ var ts; // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; - var parts; if (startLine === endLine) { if (!firstLineIsIndented) { // treat as single line comment @@ -99938,18 +103173,18 @@ var ts; } return; } - else { - parts = []; - var startPos = commentRange.pos; - for (var line = startLine; line < endLine; line++) { - var endOfLine = ts.getEndLinePosition(line, sourceFile); - parts.push({ pos: startPos, end: endOfLine }); - startPos = ts.getStartPositionOfLine(line + 1, sourceFile); - } - if (indentFinalLine) { - parts.push({ pos: startPos, end: commentRange.end }); - } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } + if (parts.length === 0) + return; var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); if (indentation === nonWhitespaceColumnInFirstPart.column) { @@ -100075,56 +103310,47 @@ var ts; /** * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ - function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword - tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } + function getRangeOfEnclosingComment(sourceFile, position, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); } + var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc); + if (jsdoc) + tokenAtPosition = jsdoc.parent; var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { return undefined; } - if (precedingToken === undefined) { - precedingToken = ts.findPrecedingToken(position, sourceFile); - } + precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken; // Between two consecutive tokens, all comments are either trailing on the former // or leading on the latter (and none are in both lists). var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end); var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); - var commentRanges = trailingRangesOfPreviousToken && leadingCommentRangesOfNextToken ? - trailingRangesOfPreviousToken.concat(leadingCommentRangesOfNextToken) : - trailingRangesOfPreviousToken || leadingCommentRangesOfNextToken; - if (commentRanges) { - for (var _i = 0, commentRanges_1 = commentRanges; _i < commentRanges_1.length; _i++) { - var range = commentRanges_1[_i]; - // The end marker of a single-line comment does not include the newline character. - // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): - // - // // asdf ^\n - // - // But for closed multi-line comments, we don't want to be inside the comment in the following case: - // - // /* asdf */^ - // - // However, unterminated multi-line comments *do* contain their end. - // - // Internally, we represent the end of the comment at the newline and closing '/', respectively. - // - if ((range.pos < position && position < range.end || - position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()))) { - return (range.kind === 3 /* MultiLineCommentTrivia */ || !onlyMultiLine) && (!predicate || predicate(range)) ? range : undefined; - } - } - } - return undefined; + var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken); + return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) || + // The end marker of a single-line comment does not include the newline character. + // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for closed multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // However, unterminated multi-line comments *do* contain their end. + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + // + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); }); } formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { case 155 /* Constructor */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (node.typeParameters === list) { return 27 /* LessThanToken */; } @@ -100132,8 +103358,8 @@ var ts; return 19 /* OpenParenToken */; } break; - case 187 /* CallExpression */: - case 188 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: if (node.typeArguments === list) { return 27 /* LessThanToken */; } @@ -100238,9 +103464,9 @@ var ts; if (options.indentStyle === ts.IndentStyle.None) { return 0; } - var precedingToken = ts.findPrecedingToken(position, sourceFile); - var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ true, precedingToken || null); // tslint:disable-line:no-null-keyword - if (enclosingCommentRange) { + var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); // tslint:disable-line:no-null-keyword + if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) { return getCommentIndent(sourceFile, position, options, enclosingCommentRange); } if (!precedingToken) { @@ -100258,7 +103484,7 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 200 /* BinaryExpression */) { + if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 202 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -100414,7 +103640,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 274 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 277 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -100462,7 +103688,7 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 217 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 220 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -100480,13 +103706,13 @@ var ts; switch (node.parent.kind) { case 162 /* TypeReference */: return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); - case 184 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return node.parent.properties; - case 183 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return node.parent.elements; - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 158 /* CallSignature */: @@ -100497,21 +103723,27 @@ var ts; return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || getListIfStartEndIsInListRange(node.parent.parameters, start, end); } - case 235 /* ClassDeclaration */: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); - case 188 /* NewExpression */: - case 187 /* CallExpression */: { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 301 /* JSDocTemplateTag */: { + var typeParameters = node.parent.typeParameters; + return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end); + } + case 190 /* NewExpression */: + case 189 /* CallExpression */: { var start = node.getStart(sourceFile); return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || getListIfStartEndIsInListRange(node.parent.arguments, start, end); } - case 233 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); - case 247 /* NamedImports */: - case 251 /* NamedExports */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); - case 180 /* ObjectBindingPattern */: - case 181 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); } } @@ -100551,10 +103783,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 187 /* CallExpression */: - case 188 /* NewExpression */: - case 185 /* PropertyAccessExpression */: - case 186 /* ElementAccessExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: node = node.expression; break; default: @@ -100619,82 +103851,82 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 216 /* ExpressionStatement */: - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 236 /* InterfaceDeclaration */: - case 238 /* EnumDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 183 /* ArrayLiteralExpression */: - case 213 /* Block */: - case 240 /* ModuleBlock */: - case 184 /* ObjectLiteralExpression */: + case 219 /* ExpressionStatement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 185 /* ArrayLiteralExpression */: + case 216 /* Block */: + case 243 /* ModuleBlock */: + case 186 /* ObjectLiteralExpression */: case 166 /* TypeLiteral */: - case 177 /* MappedType */: + case 179 /* MappedType */: case 168 /* TupleType */: - case 241 /* CaseBlock */: - case 267 /* DefaultClause */: - case 266 /* CaseClause */: - case 191 /* ParenthesizedExpression */: - case 185 /* PropertyAccessExpression */: - case 187 /* CallExpression */: - case 188 /* NewExpression */: - case 214 /* VariableStatement */: - case 249 /* ExportAssignment */: - case 225 /* ReturnStatement */: - case 201 /* ConditionalExpression */: - case 181 /* ArrayBindingPattern */: - case 180 /* ObjectBindingPattern */: - case 257 /* JsxOpeningElement */: - case 260 /* JsxOpeningFragment */: - case 256 /* JsxSelfClosingElement */: - case 265 /* JsxExpression */: + case 244 /* CaseBlock */: + case 270 /* DefaultClause */: + case 269 /* CaseClause */: + case 193 /* ParenthesizedExpression */: + case 187 /* PropertyAccessExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 217 /* VariableStatement */: + case 252 /* ExportAssignment */: + case 228 /* ReturnStatement */: + case 203 /* ConditionalExpression */: + case 183 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 260 /* JsxOpeningElement */: + case 263 /* JsxOpeningFragment */: + case 259 /* JsxSelfClosingElement */: + case 268 /* JsxExpression */: case 153 /* MethodSignature */: case 158 /* CallSignature */: case 159 /* ConstructSignature */: case 149 /* Parameter */: case 163 /* FunctionType */: case 164 /* ConstructorType */: - case 173 /* ParenthesizedType */: - case 189 /* TaggedTemplateExpression */: - case 197 /* AwaitExpression */: - case 251 /* NamedExports */: - case 247 /* NamedImports */: - case 252 /* ExportSpecifier */: - case 248 /* ImportSpecifier */: + case 175 /* ParenthesizedType */: + case 191 /* TaggedTemplateExpression */: + case 199 /* AwaitExpression */: + case 254 /* NamedExports */: + case 250 /* NamedImports */: + case 255 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: case 152 /* PropertyDeclaration */: return true; - case 232 /* VariableDeclaration */: - case 270 /* PropertyAssignment */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 184 /* ObjectLiteralExpression */) { // TODO: GH#18217 + case 235 /* VariableDeclaration */: + case 273 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 186 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } return true; - case 218 /* DoStatement */: - case 219 /* WhileStatement */: - case 221 /* ForInStatement */: - case 222 /* ForOfStatement */: - case 220 /* ForStatement */: - case 217 /* IfStatement */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 223 /* ForStatement */: + case 220 /* IfStatement */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: case 154 /* MethodDeclaration */: - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: case 155 /* Constructor */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return childKind !== 213 /* Block */; - case 250 /* ExportDeclaration */: - return childKind !== 251 /* NamedExports */; - case 244 /* ImportDeclaration */: - return childKind !== 245 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 247 /* NamedImports */); - case 255 /* JsxElement */: - return childKind !== 258 /* JsxClosingElement */; - case 259 /* JsxFragment */: - return childKind !== 261 /* JsxClosingFragment */; - case 170 /* IntersectionType */: - case 169 /* UnionType */: + return childKind !== 216 /* Block */; + case 253 /* ExportDeclaration */: + return childKind !== 254 /* NamedExports */; + case 247 /* ImportDeclaration */: + return childKind !== 248 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 250 /* NamedImports */); + case 258 /* JsxElement */: + return childKind !== 261 /* JsxClosingElement */; + case 262 /* JsxFragment */: + return childKind !== 264 /* JsxClosingFragment */; + case 172 /* IntersectionType */: + case 171 /* UnionType */: if (childKind === 166 /* TypeLiteral */) { return false; } @@ -100706,18 +103938,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 225 /* ReturnStatement */: - case 229 /* ThrowStatement */: { - if (parent.kind !== 213 /* Block */) { - return true; - } - var grandParent = parent.parent; - // In a function, we may want to write inner functions after this. - return !(grandParent && grandParent.kind === 192 /* FunctionExpression */ || grandParent.kind === 234 /* FunctionDeclaration */); - } - case 223 /* ContinueStatement */: - case 224 /* BreakStatement */: - return true; + case 228 /* ReturnStatement */: + case 232 /* ThrowStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: + return parent.kind !== 216 /* Block */; default: return false; } @@ -100845,7 +104070,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 184 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 186 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -100861,8 +104086,8 @@ var ts; this.formatContext = formatContext; this.changes = []; this.newFiles = []; - this.deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map + this.deletedNodes = []; } ChangeTracker.fromContext = function (context) { return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); @@ -100876,13 +104101,11 @@ var ts; this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; }; - /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ - ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { - if (options === void 0) { options = {}; } - var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); - var endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - return this; + ChangeTracker.prototype.delete = function (sourceFile, node) { + this.deletedNodes.push({ sourceFile: sourceFile, node: node }); + }; + ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { + this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } @@ -100897,30 +104120,6 @@ var ts; var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); }; - ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { - var containingList = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); - if (!containingList) { - ts.Debug.fail("node is not a list element"); - return this; - } - var index = ts.indexOfNode(containingList, node); - if (index < 0) { - return this; - } - if (containingList.length === 1) { - this.deleteNode(sourceFile, node); - return this; - } - // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. - // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. - ts.Debug.assert(!this.deletedNodesInLists.has(node), "Deleting a node twice"); - this.deletedNodesInLists.add(node); - this.deleteRange(sourceFile, { - pos: startPositionToDeleteNodeInList(sourceFile, node), - end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), - }); - return this; - }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); @@ -100986,7 +104185,7 @@ var ts; // If so, we do not want to separate the node from its comment if we can. // Otherwise, add an extra new line immediately before the error span. var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); - var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position); var indent = sourceFile.text.slice(lineStartPosition, startPosition); var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); @@ -101010,7 +104209,7 @@ var ts; } } else { - endNode = node.kind !== 232 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = node.kind !== 235 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; @@ -101029,6 +104228,9 @@ var ts; else if (ts.isParameter(before)) { return {}; } + else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) { + return { suffix: ", " }; + } return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it }; ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { @@ -101088,6 +104290,9 @@ var ts; var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); }; + ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) { + this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " }); + }; ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); @@ -101108,32 +104313,34 @@ var ts; return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { - if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { - return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - } - else if (ts.isStatement(node) || ts.isClassOrTypeElement(node)) { - return { suffix: this.newLineCharacter }; - } - else if (ts.isVariableDeclaration(node) || ts.isStringLiteral(node)) { - return { prefix: ", " }; - } - else if (ts.isPropertyAssignment(node)) { - return { suffix: "," + this.newLineCharacter }; - } - else if (ts.isParameter(node)) { - return {}; + switch (node.kind) { + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + case 235 /* VariableDeclaration */: + case 9 /* StringLiteral */: + case 71 /* Identifier */: + return { prefix: ", " }; + case 273 /* PropertyAssignment */: + return { suffix: "," + this.newLineCharacter }; + case 84 /* ExportKeyword */: + return { prefix: " " }; + case 149 /* Parameter */: + return {}; + default: + ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it + return { suffix: this.newLineCharacter }; } - return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 193 /* ArrowFunction */) { + if (node.kind === 195 /* ArrowFunction */) { var arrow = ts.findChildOfKind(node, 36 /* EqualsGreaterThanToken */, sourceFile); var lparen = ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile); if (lparen) { // `() => {}` --> `function f() {}` this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(89 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); - this.deleteNode(sourceFile, arrow); + deleteNode(this, sourceFile, arrow); } else { // `x => {}` -> `function f(x) {}` @@ -101141,14 +104348,14 @@ var ts; // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` this.replaceRange(sourceFile, arrow, ts.createToken(20 /* CloseParenToken */)); } - if (node.body.kind !== 213 /* Block */) { + if (node.body.kind !== 216 /* Block */) { // `() => 0` => `function f() { return 0; }` this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(17 /* OpenBraceToken */), ts.createToken(96 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(25 /* SemicolonToken */), ts.createToken(18 /* CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 192 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 194 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } }; @@ -101174,7 +104381,7 @@ var ts; if (index !== containingList.length - 1) { // any element except the last one // use next sibling as an anchor - var nextToken = ts.getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end); if (nextToken && isSeparator(after, nextToken)) { // for list // a, b, c @@ -101279,14 +104486,30 @@ var ts; } }); }; - ChangeTracker.prototype.finishTrailingCommaAfterDeletingNodesInList = function () { + ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; - this.deletedNodesInLists.forEach(function (node) { + var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_18 = function (sourceFile, node) { + if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { + if (ts.isArray(node)) { + this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); + } + else { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } + } + }; + var this_1 = this; + for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; + _loop_18(sourceFile, node); + } + deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); if (node !== ts.last(list)) return; - var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !_this.deletedNodesInLists.has(n); }, list.length - 2); + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2); if (lastNonDeletedIndex !== -1) { _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); } @@ -101299,8 +104522,8 @@ var ts; * so we can only call this once and can't get the non-formatted text separately. */ ChangeTracker.prototype.getChanges = function (validate) { + this.finishDeleteDeclarations(); this.finishClassesWithNodesInsertedAtStart(); - this.finishTrailingCommaAfterDeletingNodesInList(); var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; @@ -101329,14 +104552,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_10 = function (i) { + var _loop_19 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_10(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -101397,8 +104620,8 @@ var ts; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { - var change = changes[i]; - text = "" + text.substring(0, change.span.start) + change.newText + text.substring(ts.textSpanEnd(change.span)); + var _a = changes[i], span = _a.span, newText = _a.newText; + text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span)); } return text; } @@ -101600,6 +104823,165 @@ var ts; return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 147 /* ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } + var deleteDeclaration; + (function (deleteDeclaration_1) { + function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { + switch (node.kind) { + case 149 /* Parameter */: { + var oldFunction = node.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, + /*parameters*/ undefined, // TODO: GH#18217 + oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + // Drop leading and trailing trivia of the new function because we're only going + // to replace the span (vs the full span) of the old function - the old leading + // and trailing trivia will remain. + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceNode(sourceFile, oldFunction, newFunction); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + } + case 247 /* ImportDeclaration */: + deleteNode(changes, sourceFile, node, + // For first import, leave header comment in place + node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); + break; + case 184 /* BindingElement */: + var pattern = node.parent; + var preserveComma = pattern.kind === 183 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + if (preserveComma) { + deleteNode(changes, sourceFile, node); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 235 /* VariableDeclaration */: + deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); + break; + case 148 /* TypeParameter */: + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + break; + case 251 /* ImportSpecifier */: + var namedImports = node.parent; + if (namedImports.elements.length === 1) { + deleteImportBinding(changes, sourceFile, namedImports); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 249 /* NamespaceImport */: + deleteImportBinding(changes, sourceFile, node); + break; + default: + if (ts.isImportClause(node.parent) && node.parent.name === node) { + deleteDefaultImport(changes, sourceFile, node.parent); + } + else if (ts.isCallLikeExpression(node.parent)) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + else { + deleteNode(changes, sourceFile, node, node.kind === 25 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + } + } + } + deleteDeclaration_1.deleteDeclaration = deleteDeclaration; + function deleteDefaultImport(changes, sourceFile, importClause) { + if (!importClause.namedBindings) { + // Delete the whole import + deleteNode(changes, sourceFile, importClause.parent); + } + else { + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + deleteNode(changes, sourceFile, importClause.name); + } + } + } + function deleteImportBinding(changes, sourceFile, node) { + if (node.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1)); + changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end }); + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(node, 247 /* ImportDeclaration */); + deleteNode(changes, sourceFile, importDecl); + } + } + function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { + var parent = node.parent; + if (parent.kind === 272 /* CatchClause */) { + // TODO: There's currently no unused diagnostic for this, could be a suggestion + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 19 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 20 /* CloseParenToken */, sourceFile)); + return; + } + if (parent.declarations.length !== 1) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + return; + } + var gp = parent.parent; + switch (gp.kind) { + case 225 /* ForOfStatement */: + case 224 /* ForInStatement */: + changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); + break; + case 223 /* ForStatement */: + deleteNode(changes, sourceFile, parent); + break; + case 217 /* VariableStatement */: + deleteNode(changes, sourceFile, gp); + break; + default: + ts.Debug.assertNever(gp); + } + } + })(deleteDeclaration || (deleteDeclaration = {})); + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ + // Exported for tests only! (TODO: improve tests to not need this) + function deleteNode(changes, sourceFile, node, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, node, options); + changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + } + textChanges_3.deleteNode = deleteNode; + function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) { + var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile)); + var index = ts.indexOfNode(containingList, node); + ts.Debug.assert(index !== -1); + if (containingList.length === 1) { + deleteNode(changes, sourceFile, node); + return; + } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice"); + deletedNodesInLists.add(node); + changes.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); + } })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); /* @internal */ @@ -101655,15 +105037,14 @@ var ts; function createCombinedCodeActions(changes, commands) { return { changes: changes, commands: commands }; } + codefix.createCombinedCodeActions = createCombinedCodeActions; function createFileTextChanges(fileName, textChanges) { return { fileName: fileName, textChanges: textChanges }; } codefix.createFileTextChanges = createFileTextChanges; function codeFixAll(context, errorCodes, use) { var commands = []; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); - }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); }); return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; @@ -101676,6 +105057,7 @@ var ts; } } } + codefix.eachDiagnostic = eachDiagnostic; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -101726,7 +105108,7 @@ var ts; getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, }); function makeChange(changeTracker, sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); var decorator = ts.findAncestor(token, ts.isDecorator); ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); @@ -101758,7 +105140,7 @@ var ts; }); }, }); function getDeclaration(file, pos) { - var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false); + var name = ts.getTokenAtPosition(file, pos); // For an arrow function with no name, 'name' lands on the first parameter. return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); } @@ -101805,24 +105187,24 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 232 /* VariableDeclaration */ || + node.kind === 235 /* VariableDeclaration */ || node.kind === 151 /* PropertySignature */ || node.kind === 152 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 279 /* JSDocAllType */: - case 280 /* JSDocUnknownType */: + case 282 /* JSDocAllType */: + case 283 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 283 /* JSDocOptionalType */: + case 286 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 282 /* JSDocNonNullableType */: + case 285 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 281 /* JSDocNullableType */: + case 284 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 285 /* JSDocVariadicType */: + case 288 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 284 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: return transformJSDocFunctionType(node); case 162 /* TypeReference */: return transformJSDocTypeReference(node); @@ -101846,7 +105228,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 285 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 288 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -101912,8 +105294,7 @@ var ts; getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, }); function doChange(changes, sourceFile, position, checker) { - var deletedNodes = []; - var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false)); + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { // Bad input return undefined; @@ -101922,20 +105303,20 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: precedingNode = ctorDeclaration; - deleteNode(ctorDeclaration); + changes.delete(sourceFile, ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 - deleteNode(precedingNode); + changes.delete(sourceFile, precedingNode); } else { - deleteNode(ctorDeclaration, /*inList*/ true); + changes.delete(sourceFile, ctorDeclaration); } break; } @@ -101945,22 +105326,6 @@ var ts; ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile); // Because the preceding node could be touched, we need to insert nodes before delete nodes. changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); - for (var _i = 0, deletedNodes_1 = deletedNodes; _i < deletedNodes_1.length; _i++) { - var _a = deletedNodes_1[_i], node = _a.node, inList = _a.inList; - if (inList) { - changes.deleteNodeInList(sourceFile, node); - } - else { - changes.deleteNode(sourceFile, node); - } - } - function deleteNode(node, inList) { - if (inList === void 0) { inList = false; } - // If parent node has already been deleted, do nothing - if (!deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n.node); })) { - deletedNodes.push({ node: node, inList: inList }); - } - } function createClassElementsFromSymbol(symbol) { var memberElements = []; // all instance members are stored in the "member" array of symbol @@ -101998,15 +105363,15 @@ var ts; return; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 216 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 219 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; - deleteNode(nodeToDelete); + changes.delete(sourceFile, nodeToDelete); if (!assignmentBinaryExpression.right) { return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 192 /* FunctionExpression */: { + case 194 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, @@ -102014,12 +105379,12 @@ var ts; ts.copyComments(assignmentBinaryExpression, method, sourceFile); return method; } - case 193 /* ArrowFunction */: { + case 195 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 213 /* Block */) { + if (arrowFunctionBody.kind === 216 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] @@ -102047,7 +105412,7 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 192 /* FunctionExpression */) { + if (!initializer || initializer.kind !== 194 /* FunctionExpression */) { return undefined; } if (node.name.kind !== 71 /* Identifier */) { @@ -102082,6 +105447,442 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertToAsyncFunction"; + var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, + }); + function convertToAsyncFunction(changes, sourceFile, position, checker, context) { + // get the function declaration - returns a promise + var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + if (!functionToConvert) { + return; + } + var synthNamesMap = ts.createMap(); + var originalTypeMap = ts.createMap(); + var allVarNames = []; + var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); + var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + var constIdentifiers = getConstIdentifiers(synthNamesMap); + var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + if (!returnStatements.length) { + return; + } + // add the async keyword + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + function startTransformation(node, nodeToReplace) { + var newNodes = transformExpression(node, transformer, node); + changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); + } + var _loop_20 = function (statement) { + if (ts.isCallExpression(statement)) { + startTransformation(statement, statement); + } + else { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + }; + for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { + var statement = returnStatements_1[_i]; + _loop_20(statement); + } + } + // Returns the identifiers that are never reassigned in the refactor + function getConstIdentifiers(synthNamesMap) { + var constIdentifiers = []; + synthNamesMap.forEach(function (val) { + if (val.numberOfAssignmentsOriginal === 0) { + constIdentifiers.push(val.identifier); + } + }); + return constIdentifiers; + } + /* + Finds all of the expressions of promise type that should not be saved in a variable during the refactor + */ + function getAllPromiseExpressionsToReturn(func, checker) { + if (!func.body) { + return ts.createMap(); + } + var setOfExpressionsToReturn = ts.createMap(); + ts.forEachChild(func.body, function visit(node) { + if (isPromiseReturningExpression(node, checker, "then")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + ts.forEach(node.arguments, visit); + } + else if (isPromiseReturningExpression(node, checker, "catch")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned + ts.forEachChild(node, visit); + } + else if (isPromiseReturningExpression(node, checker)) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // don't recurse here, since we won't refactor any children or arguments of the expression + } + else { + ts.forEachChild(node, visit); + } + }); + return setOfExpressionsToReturn; + } + /* + Returns true if node is a promise returning expression + If name is not undefined, node is a promise returning call of name + */ + function isPromiseReturningExpression(node, checker, name) { + var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); + var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); + return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); + } + function declaredInFile(symbol, sourceFile) { + return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile; + } + /* + Renaming of identifiers may be neccesary as the refactor changes scopes - + This function collects all existing identifier names and names of identifiers that will be created in the refactor. + It then checks for any collisions and renames them through getSynthesizedDeepClone + */ + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { + var identsToRenameMap = ts.createMap(); // key is the symbol id + ts.forEachChild(nodeToRename, function visit(node) { + if (!ts.isIdentifier(node)) { + ts.forEachChild(node, visit); + return; + } + var symbol = checker.getSymbolAtLocation(node); + var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile); + if (symbol && isDefinedInFile) { + var type = checker.getTypeAtLocation(node); + var lastCallSignature = getLastCallSignature(type, checker); + var symbolIdString = ts.getSymbolId(symbol).toString(); + // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) + // Note - the choice of the last call signature is arbitrary + if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { + var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + synthNamesMap.set(symbolIdString, synthName); + allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + } + // we only care about identifiers that are parameters and declarations (don't care about other uses) + else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + // if the identifier name conflicts with a different identifier that we've already seen + if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { + var newName = getNewNameIfConflict(node, allVarNames); + identsToRenameMap.set(symbolIdString, newName.identifier); + synthNamesMap.set(symbolIdString, newName); + allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + } + else { + var identifier = ts.getSynthesizedDeepClone(node); + identsToRenameMap.set(symbolIdString, identifier); + synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); + if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { + allVarNames.push({ identifier: identifier, symbol: symbol }); + } + } + } + } + }); + return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback); + function isExpressionOrCallOnTypePromise(child) { + var node = child.parent; + if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) { + var nodeType = checker.getTypeAtLocation(node); + var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType); + return !!isPromise; + } + return false; + } + function deepCloneCallback(node, clone) { + if (ts.isIdentifier(node)) { + var symbol = checker.getSymbolAtLocation(node); + var symboldIdString = symbol && ts.getSymbolId(symbol).toString(); + var renameInfo = symbol && synthNamesMap.get(symboldIdString); + if (renameInfo) { + var type = checker.getTypeAtLocation(node); + if (type) { + originalType.set(ts.getNodeId(clone).toString(), type); + } + } + } + var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); + if (val !== undefined) { + setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString()); + setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val); + } + } + } + function getNewNameIfConflict(name, allVarNames) { + var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + var numberOfAssignmentsOriginal = 0; + var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); + return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + // dispatch function to recursively build the refactoring + function transformExpression(node, transformer, outermostParent, prevArgName) { + if (!node) { + return []; + } + var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); + var nodeType = originalType || transformer.checker.getTypeAtLocation(node); + if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformThen(node, transformer, outermostParent, prevArgName); + } + else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformCatch(node, transformer, prevArgName); + } + else if (ts.isPropertyAccessExpression(node)) { + return transformExpression(node.expression, transformer, outermostParent, prevArgName); + } + else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformPromiseCall(node, transformer, prevArgName); + } + return []; + } + function transformCatch(node, transformer, prevArgName) { + var func = node.arguments[0]; + var argName = getArgName(func, transformer); + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + /* + If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) + To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap + We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step + */ + if (prevArgName && !shouldReturn) { + prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block + transformer.synthNamesMap.forEach(function (val, key) { + if (val.identifier.text === prevArgName.identifier.text) { + transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + } + }); + // update the constIdentifiers list + if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { + transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + } + } + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); + var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); + var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); + /* + In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) + */ + var varDeclList; + if (prevArgName && !shouldReturn) { + var typeArray = prevArgName.types; + var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var varDecl = [ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)]; + varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); + } + var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); + return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; + } + function transformThen(node, transformer, outermostParent, prevArgName) { + var _a = node.arguments, res = _a[0], rej = _a[1]; + if (!res) { + return transformExpression(node.expression, transformer, outermostParent); + } + var argNameRes = getArgName(res, transformer); + var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); + if (rej) { + var argNameRej = getArgName(rej, transformer); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); + var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); + var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); + return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; + } + else { + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + } + return []; + } + function getFlagOfIdentifier(node, constIdentifiers) { + var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); + return inArr ? 2 /* Const */ : 1 /* Let */; + } + function transformPromiseCall(node, transformer, prevArgName) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call + var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; + var originalNodeParent = node.original ? node.original.parent : node.parent; + if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + } + else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return [ts.createStatement(ts.createAwait(node))]; + } + return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; + } + function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + } + return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + } + function getTransformationBody(func, prevArgName, argName, parent, transformer) { + var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; + var hasArgName = argName && argName.identifier.text.length > 0; + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); + switch (func.kind) { + case 71 /* Identifier */: + if (!hasArgName) + break; + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return ts.createNodeArray([ts.createReturn(synthCall)]); + } + if (!hasPrevArgName) + break; + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); + var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); + var returnType = callSignatures && callSignatures[0].getReturnType(); + var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); + prevArgName.types.push(returnType); + return varDeclOrAssignment; + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + // Arrow functions with block bodies { } will enter this control flow + if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + var refactoredStmts = []; + for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { + refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + } + else { + refactoredStmts.push(statement); + } + } + return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : + removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + } + else { + var funcBody = func.body; + var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); + var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); + if (innerCbBody.length > 0) { + return ts.createNodeArray(innerCbBody); + } + if (hasPrevArgName && !shouldReturn) { + var type_3 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); + var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); + prevArgName.types.push(returnType_1); + return varDeclOrAssignment_1; + } + else { + return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + } + } + break; + } + return ts.createNodeArray([]); + } + function getLastCallSignature(type, checker) { + var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); + return callSignatures && callSignatures[callSignatures.length - 1]; + } + function removeReturns(stmts, prevArgName, constIdentifiers) { + var ret = []; + for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { + var stmt = stmts_1[_i]; + if (ts.isReturnStatement(stmt)) { + if (stmt.expression) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + } + } + else { + ret.push(ts.getSynthesizedDeepClone(stmt)); + } + } + return ts.createNodeArray(ret); + } + function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { + var innerCbBody = []; + for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) { + var stmt = innerRetStmts_1[_i]; + ts.forEachChild(stmt, function visit(node) { + if (ts.isCallExpression(node)) { + var temp = transformExpression(node, transformer, node, prevArgName); + innerCbBody = innerCbBody.concat(temp); + if (innerCbBody.length > 0) { + return; + } + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + return innerCbBody; + } + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + function getArgName(funcNode, transformer) { + var numberOfAssignmentsOriginal = 0; + var types = []; + var name; + if (ts.isFunctionLikeDeclaration(funcNode)) { + if (funcNode.parameters.length > 0) { + var param = funcNode.parameters[0].name; + name = getMapEntryIfExists(param); + } + } + else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { + name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + else if (ts.isIdentifier(funcNode)) { + name = getMapEntryIfExists(funcNode); + } + if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { + return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + return name; + function getMapEntryIfExists(identifier) { + var originalNode = getOriginalNode(identifier); + var symbol = getSymbol(originalNode); + if (!symbol) { + return { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString()); + return mapEntry || { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + function getSymbol(node) { + return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node); + } + function getOriginalNode(node) { + return node.original ? node.original : node; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -102111,10 +105912,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 187 /* CallExpression */: + case 189 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -102167,20 +105968,20 @@ var ts; } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 216 /* ExpressionStatement */: { + case 219 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 187 /* CallExpression */: { + case 189 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 200 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var operatorToken = expression.operatorToken; return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); } @@ -102222,8 +106023,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 180 /* ObjectBindingPattern */: - case 181 /* ArrayBindingPattern */: { + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ @@ -102246,7 +106047,7 @@ var ts; if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { // `const alias = module.exports;` or `module.exports = alias;` can be removed. - changes.deleteNode(sourceFile, assignment.parent); + changes.delete(sourceFile, assignment.parent); } else { var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) @@ -102277,10 +106078,10 @@ var ts; case 156 /* GetAccessor */: case 157 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 271 /* ShorthandPropertyAssignment */: - case 272 /* SpreadAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 275 /* SpreadAssignment */: return undefined; - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); case 154 /* MethodDeclaration */: return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); @@ -102337,7 +106138,7 @@ var ts; changes.insertName(sourceFile, right, name); var semi = ts.findChildOfKind(parent, 25 /* SemicolonToken */, sourceFile); if (semi) - changes.deleteNode(sourceFile, semi, { useNonAdjustedEndPosition: true }); + changes.delete(sourceFile, semi); } else { // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` @@ -102348,7 +106149,7 @@ var ts; function convertExportsDotXEquals_replaceNode(name, exported) { var modifiers = [ts.createToken(84 /* ExportKeyword */)]; switch (exported.kind) { - case 192 /* FunctionExpression */: { + case 194 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -102356,10 +106157,10 @@ var ts; } } // falls through - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported); - case 205 /* ClassExpression */: + case 207 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported); default: @@ -102377,7 +106178,7 @@ var ts; */ function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 180 /* ObjectBindingPattern */: { + case 182 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -102388,7 +106189,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 181 /* ArrayBindingPattern */: { + case 183 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -102471,11 +106272,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return parent.name !== node; - case 182 /* BindingElement */: + case 184 /* BindingElement */: return parent.propertyName !== node; - case 248 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -102534,7 +106335,7 @@ var ts; }); }, }); function getQualifiedName(sourceFile, pos) { - var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ true), ts.isQualifiedName); + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName); ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; } @@ -102579,7 +106380,7 @@ var ts; }, }); function getClass(sourceFile, pos) { - return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false))); + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos))); } function symbolPointsToNonPrivateMember(symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); @@ -102607,7 +106408,7 @@ var ts; } } function getHeritageClauseSymbolTable(classDeclaration, checker) { - var heritageClauseNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); + var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration); if (!heritageClauseNode) return ts.createSymbolTable(); var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); @@ -102621,42 +106422,120 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var ChangeTracker = ts.textChanges.ChangeTracker; + codefix.importFixId = "fixMissingImport"; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, + ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, + ]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, - ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, - ], - getCodeActions: function (context) { return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ? getActionsForUMDImport(context) - : getActionsForNonUMDImport(context); }, - // TODO: GH#20315 - fixIds: [], - getAllCodeActions: ts.notImplemented, + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span; + var info = getFixesInfo(context, errorCode, span.start); + if (!info) + return undefined; + var fixes = info.fixes, symbolName = info.symbolName; + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); + }, + fixIds: [codefix.importFixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, preferences = context.preferences; + // Namespace fixes don't conflict, so just build a list. + var addToNamespace = []; + var importType = []; + // Keys are import clause node IDs. + var addToExisting = ts.createMap(); + // Keys are module specifiers. + var newImports = ts.createMap(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getFixesInfo(context, diag.code, diag.start); + if (!info || !info.fixes.length) + return; + var fixes = info.fixes, symbolName = info.symbolName; + var fix = ts.first(fixes); + switch (fix.kind) { + case 0 /* UseNamespace */: + addToNamespace.push(fix); + break; + case 1 /* ImportType */: + importType.push(fix); + break; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + var key = String(ts.getNodeId(importClause)); + var entry = addToExisting.get(key); + if (!entry) { + addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [] }); + } + if (importKind === 0 /* Named */) { + ts.pushIfUnique(entry.namedImports, symbolName); + } + else { + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + } + break; + } + case 3 /* AddNew */: { + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; + var entry = newImports.get(moduleSpecifier); + if (!entry) { + newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined }); + } + switch (importKind) { + case 1 /* Default */: + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + break; + case 0 /* Named */: + ts.pushIfUnique(entry.namedImports, symbolName); + break; + case 3 /* Equals */: + case 2 /* Namespace */: + ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName); + entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; + break; + } + break; + } + default: + ts.Debug.assertNever(fix); + } + }); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { + var fix = addToNamespace_1[_i]; + addNamespaceQualifier(changes, sourceFile, fix); + } + for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { + var fix = importType_1[_a]; + addImportType(changes, sourceFile, fix, quotePreference); + } + addToExisting.forEach(function (_a) { + var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; + doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); + }); + newImports.forEach(function (imports, moduleSpecifier) { + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); + }); + })); + }, }); - function createCodeAction(descriptionDiagnostic, diagnosticArgs, changes) { - // TODO: GH#20315 - return codefix.createCodeFixActionNoFixId("import", changes, [descriptionDiagnostic].concat(diagnosticArgs)); - } - function convertToImportCodeFixContext(context, symbolToken, symbolName) { - var program = context.program; - var checker = program.getTypeChecker(); - return { - host: context.host, - formatContext: context.formatContext, - sourceFile: context.sourceFile, - program: program, - checker: checker, - compilerOptions: program.getCompilerOptions(), - getCanonicalFileName: ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(context.host)), - symbolName: symbolName, - symbolToken: symbolToken, - preferences: context.preferences, - }; - } + // Sorted with the preferred fix coming first. + var ImportFixKind; + (function (ImportFixKind) { + ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; + ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType"; + ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; + })(ImportFixKind || (ImportFixKind = {})); var ImportKind; (function (ImportKind) { ImportKind[ImportKind["Named"] = 0] = "Named"; @@ -102664,13 +106543,13 @@ var ts; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; - var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences }; - return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); + return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; } codefix.getImportCompletionAction = getImportCompletionAction; function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { @@ -102684,29 +106563,25 @@ var ts; var exported = _a[_i]; if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ }); + result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); } } }); return result; } - function getCodeActionsForImport(exportInfos, context) { - var result = []; - getCodeActionsForImport_separateExistingAndNew(exportInfos, context, result, result); - return result; + function isTypeOnlySymbol(s) { + return !(s.flags & 67216319 /* Value */); } - function getCodeActionsForImport_separateExistingAndNew(exportInfos, context, useExisting, addNew) { - var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, context.checker, context.sourceFile); }); - ts.append(useExisting, tryUseExistingNamespaceImport(existingImports, context, context.symbolToken, context.checker)); - var addToExisting = tryAddToExistingImport(existingImports, context); - if (addToExisting) { - useExisting.push(addToExisting); - } - else { // Don't bother providing an action to add a new import if we can add to an existing one. - getCodeActionsForAddImport(exportInfos, context, existingImports, addNew); - } - } - function tryUseExistingNamespaceImport(existingImports, context, symbolToken, checker) { + function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { + var checker = program.getTypeChecker(); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); + var addToExisting = tryAddToExistingImport(existingImports); + // Don't bother providing an action to add a new import if we can add to an existing one. + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences); + return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); + } + function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { // It is possible that multiple import statements with the same specifier exist in the file. // e.g. // @@ -102719,186 +106594,104 @@ var ts; // 1. change "member3" to "ns.member3" // 2. add "member3" to the second import statement's import list // and it is up to the user to decide which one fits best. - return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; var namespace = getNamespaceImportName(declaration); if (namespace) { - var moduleSymbol = namespace && checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); - if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - return getCodeActionForUseExistingNamespaceImport(namespace.text, context, symbolToken); + var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; } } }); } - function tryAddToExistingImport(existingImports, context) { + function tryAddToExistingImport(existingImports) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 244 /* ImportDeclaration */ && declaration.importClause) { - var changes = tryUpdateExistingImport(context, declaration.importClause, importKind); - if (changes) { - var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); - return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [context.symbolName, moduleSpecifierWithoutQuotes], changes); - } - } + if (declaration.kind !== 247 /* ImportDeclaration */) + return undefined; + var importClause = declaration.importClause; + if (!importClause) + return undefined; + var name = importClause.name, namedBindings = importClause.namedBindings; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) + ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } + : undefined; }); } function getNamespaceImportName(declaration) { - if (declaration.kind === 244 /* ImportDeclaration */) { + if (declaration.kind === 247 /* ImportDeclaration */) { var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 246 /* NamespaceImport */ ? namedBindings.name : undefined; + return namedBindings && namedBindings.kind === 249 /* NamespaceImport */ ? namedBindings.name : undefined; } else { return declaration.name; } } - function getExistingImportDeclarations(_a, checker, _b) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var imports = _b.imports; - return ts.mapDefined(imports, function (moduleSpecifier) { + function getExistingImportDeclarations(_a, checker, sourceFile) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + // Can't use an es6 import for a type in JS. + return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 244 /* ImportDeclaration */ || i.kind === 243 /* ImportEqualsDeclaration */) + return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } - function getCodeActionForNewImport(context, _a) { - var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; - var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences; - var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifierWithoutQuotes, ts.getQuotePreference(sourceFile, preferences)); - var importDecl = importKind !== 3 /* Equals */ - ? ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, createImportClauseOfKind(importKind, symbolName), quotedModuleSpecifier) - : ts.createImportEqualsDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); - var changes = ChangeTracker.with(context, function (changeTracker) { - if (lastImportDeclaration) { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); - } - else { - changeTracker.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); - } - }); - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line separating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); - } - function createImportClauseOfKind(kind, symbolName) { - var id = ts.createIdentifier(symbolName); - switch (kind) { - case 1 /* Default */: - return ts.createImportClause(id, /*namedBindings*/ undefined); - case 2 /* Namespace */: - return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(id)); - case 0 /* Named */: - return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, id)])); - default: - ts.Debug.assertNever(kind); - } - } - function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { + function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { + var isJs = ts.isSourceFileJavaScript(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); + return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. + return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; + }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getCodeActionsForAddImport(exportInfos, ctx, existingImports, addNew) { + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); - var newImportInfos = existingDeclaration - ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences); - for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) { - var info = newImportInfos_1[_i]; - addNew.push(getCodeActionForNewImport(ctx, info)); - } + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); } function newImportInfoFromExistingSpecifier(_a) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 244 /* ImportDeclaration */ + var expression = declaration.kind === 247 /* ImportDeclaration */ ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 254 /* ExternalModuleReference */ + : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ ? declaration.moduleReference.expression : undefined; - return expression && ts.isStringLiteral(expression) ? { moduleSpecifier: expression.text, importKind: importKind } : undefined; - } - function tryUpdateExistingImport(context, importClause, importKind) { - var symbolName = context.symbolName, sourceFile = context.sourceFile; - var name = importClause.name; - var namedBindings = (importClause.kind !== 243 /* ImportEqualsDeclaration */ && importClause).namedBindings; // TODO: GH#18217 - switch (importKind) { - case 1 /* Default */: - return name ? undefined : ChangeTracker.with(context, function (t) { - return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); - }); - case 0 /* Named */: { - var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName)); - if (namedBindings && namedBindings.kind === 247 /* NamedImports */ && namedBindings.elements.length !== 0) { - // There are already named imports; add another. - return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); - } - if (!namedBindings || namedBindings.kind === 247 /* NamedImports */ && namedBindings.elements.length === 0) { - return ChangeTracker.with(context, function (t) { - return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); - }); - } - return undefined; - } - case 2 /* Namespace */: - return namedBindings ? undefined : ChangeTracker.with(context, function (t) { - return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); - }); - case 3 /* Equals */: - return undefined; - default: - ts.Debug.assertNever(importKind); - } + return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; } - function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { - var symbolName = context.symbolName, sourceFile = context.sourceFile; - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - var changes = ChangeTracker.with(context, function (tracker) { - return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken)); - }); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes); + function getFixesInfo(context, errorCode, pos) { + var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); + var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getFixesInfoForUMDImport(context, symbolToken) + : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined; + return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); } - function getActionsForUMDImport(context) { - var token = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var umdSymbol; - if (ts.isIdentifier(token)) { - // try the identifier to see if it is the umd symbol - umdSymbol = checker.getSymbolAtLocation(token); - } - if (!ts.isUMDExportSymbol(umdSymbol)) { - // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - var parent = token.parent; - var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent); - if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 260 /* JsxOpeningFragment */) { - umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false); - } - } - if (ts.isUMDExportSymbol(umdSymbol)) { - var symbol = checker.getAliasedSymbol(umdSymbol); - if (symbol) { - return getCodeActionsForImport([{ moduleSymbol: symbol, importKind: getUmdImportKind(context.program.getCompilerOptions()) }], convertToImportCodeFixContext(context, token, umdSymbol.name)); - } - } - return undefined; + function getFixesInfoForUMDImport(_a, token) { + var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + var umdSymbol = getUmdSymbol(token, checker); + if (!umdSymbol) + return undefined; + var symbol = checker.getAliasedSymbol(umdSymbol); + var symbolName = umdSymbol.name; + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); + return { fixes: fixes, symbolName: symbolName }; + } + function getUmdSymbol(token, checker) { + // try the identifier to see if it is the umd symbol + var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined; + if (ts.isUMDExportSymbol(umdSymbol)) + return umdSymbol; + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + var parent = token.parent; + return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + : undefined; } function getUmdImportKind(compilerOptions) { // Import a synthetic `default` if enabled. @@ -102922,69 +106715,160 @@ var ts; return ts.Debug.assertNever(moduleKind); } } - function getActionsForNonUMDImport(context) { - // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. - var sourceFile = context.sourceFile, span = context.span, program = context.program, cancellationToken = context.cancellationToken; + function getFixesInfoForNonUMDImport(_a, symbolToken) { + var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; var checker = program.getTypeChecker(); - var symbolToken = ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false); // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken - && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) ? checker.getJsxNamespace() - : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; - if (!symbolName) - return undefined; + : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here - ts.Debug.assert(symbolName !== "default"); - var addToExistingDeclaration = []; - var addNewDeclaration = []; - getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).forEach(function (exportInfos) { - getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration); - }); - return addToExistingDeclaration.concat(addNewDeclaration); + ts.Debug.assert(symbolName !== "default" /* Default */); + var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { + var _ = _a[0], exportInfos = _a[1]; + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences); + })); + return { fixes: fixes, symbolName: symbolName }; } + // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); // check the default export var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || - getEscapedNameForExportDefault(defaultExport) === symbolName || - moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { - addSymbol(moduleSymbol, localSymbol || defaultExport, 1 /* Default */); + var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); + if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultExport, 1 /* Default */); } } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); } - function getEscapedNameForExportDefault(symbol) { - return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { - if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.escapedText; - } + }); + return originalSymbolToExportInfos; + } + function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol) + return { symbolForMeaning: localSymbol, name: localSymbol.name }; + var name = getNameForExportDefault(defaultExport); + if (name !== undefined) + return { symbolForMeaning: defaultExport, name: name }; + if (defaultExport.flags & 2097152 /* Alias */) { + var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + } + else { + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + } + } + function getNameForExportDefault(symbol) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.text; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.text === "default" /* Default */); + return declaration.propertyName && declaration.propertyName.text; + } + }); + } + function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) { + var diag; + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); + }); + return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + } + function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { + switch (fix.kind) { + case 0 /* UseNamespace */: + addNamespaceQualifier(changes, sourceFile, fix); + return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; + case 1 /* ImportType */: + addImportType(changes, sourceFile, fix, quotePreference); + return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; + case 2 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! + } + case 3 /* AddNew */: { + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } + : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } + : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); + return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + } + default: + return ts.Debug.assertNever(fix); + } + } + function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports) { + if (defaultImport) { + ts.Debug.assert(!clause.name); + changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " }); + } + if (namedImports.length) { + var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); + if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { + for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { + var spec = specifiers_1[_i]; + changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); + } + } + else { + if (specifiers.length) { + var namedImports_1 = ts.createNamedImports(specifiers); + if (clause.namedBindings) { + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); } - else if (ts.isExportSpecifier(declaration)) { - ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); - return declaration.propertyName && declaration.propertyName.escapedText; + else { + changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name), namedImports_1); } - }); + } } - }); - return originalSymbolToExportInfos; + } + } + function addNamespaceQualifier(changes, sourceFile, _a) { + var namespacePrefix = _a.namespacePrefix, position = _a.position; + changes.insertText(sourceFile, position, namespacePrefix + "."); + } + function addImportType(changes, sourceFile, _a, quotePreference) { + var moduleSpecifier = _a.moduleSpecifier, position = _a.position; + changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); + } + function getImportTypePrefix(moduleSpecifier, quotePreference) { + var quote = ts.getQuoteFromPreference(quotePreference); + return "import(" + quote + moduleSpecifier + quote + ")."; + } + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { + var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + if (defaultImport !== undefined || namedImports.length) { + ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference)); + } + if (namespaceLikeImport) { + ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ + ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier)); + } } - function checkSymbolHasMeaning(_a, meaning) { + function symbolHasMeaning(_a, meaning) { var declarations = _a.declarations; return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); } @@ -103059,6 +106943,8 @@ var ts; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, ]; codefix.registerCodeFix({ @@ -103085,7 +106971,7 @@ var ts; // This is the identifier of the misspelled word. eg: // this.speling = 1; // ^^^^^^^ - var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); // TODO: GH#15852 + var node = ts.getTokenAtPosition(sourceFile, pos); var checker = context.program.getTypeChecker(); var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { @@ -103098,7 +106984,7 @@ var ts; var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { - suggestion = checker.getSuggestionForNonexistentModule(node, resolvedSourceFile.symbol); + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); } } else { @@ -103157,46 +107043,99 @@ var ts; var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); if (!info) return undefined; - var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, context.preferences); - var addMember = inJs ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : - getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); + if (info.kind === 0 /* Enum */) { + var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); + return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; + } + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, fixIds: [fixId], getAllCodeActions: function (context) { - var seenNames = ts.createMap(); - return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var program = context.program, preferences = context.preferences; - var info = getInfo(diag.file, diag.start, program.getTypeChecker()); - if (!info) - return; - var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - if (!ts.addToSeen(seenNames, token.text)) { - return; - } - // Always prefer to add a method declaration if possible. - if (call) { - addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, preferences); - } - else { - if (inJs) { - addMissingMemberInJs(changes, classDeclarationSourceFile, classDeclaration, token.text, makeStatic); + var program = context.program, preferences = context.preferences; + var checker = program.getTypeChecker(); + var seen = ts.createMap(); + var typeDeclToMembers = new ts.NodeMap(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, checker); + if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { + return; + } + if (info.kind === 0 /* Enum */) { + var token = info.token, parentDeclaration = info.parentDeclaration; + addEnumMemberDeclaration(changes, checker, token, parentDeclaration); } else { - var typeNode = getTypeNode(program.getTypeChecker(), classDeclaration, token); - addPropertyDeclaration(changes, classDeclarationSourceFile, classDeclaration, token.text, typeNode, makeStatic); + var parentDeclaration = info.parentDeclaration, token_2 = info.token; + var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + if (!infos.some(function (i) { return i.token.text === token_2.text; })) + infos.push(info); } - } - }); + }); + typeDeclToMembers.forEach(function (infos, classDeclaration) { + var supers = getAllSupers(classDeclaration, checker); + var _loop_21 = function (info) { + // If some superclass added this property, don't add it again. + if (supers.some(function (superClassOrInterface) { + var superInfos = typeDeclToMembers.get(superClassOrInterface); + return !!superInfos && superInfos.some(function (_a) { + var token = _a.token; + return token.text === info.token.text; + }); + })) + return "continue"; + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + } + else { + if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + } + } + }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + _loop_21(info); + } + }); + })); }, }); + function getAllSupers(decl, checker) { + var res = []; + while (decl) { + var superElement = ts.getClassExtendsHeritageElement(decl); + var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); + var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); + if (superDecl) { + res.push(superDecl); + } + decl = superDecl; + } + return res; + } + var InfoKind; + (function (InfoKind) { + InfoKind[InfoKind["Enum"] = 0] = "Enum"; + InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface"; + })(InfoKind || (InfoKind = {})); function getInfo(tokenSourceFile, tokenPos, checker) { // The identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos); if (!ts.isIdentifier(token)) { return undefined; } @@ -103205,28 +107144,36 @@ var ts; return undefined; var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression)); var symbol = leftExpressionType.symbol; - var classDeclaration = symbol && symbol.declarations && ts.find(symbol.declarations, ts.isClassLike); - if (!classDeclaration) + if (!symbol || !symbol.declarations) return undefined; - var makeStatic = leftExpressionType.target !== checker.getDeclaredTypeOfSymbol(symbol); - var classDeclarationSourceFile = classDeclaration.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(classDeclarationSourceFile); - var call = ts.tryCast(parent.parent, ts.isCallExpression); - return { token: token, classDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; - } - function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); + // Prefer to change the class instead of the interface if they are merged + var classOrInterface = ts.find(symbol.declarations, ts.isClassLike) || ts.find(symbol.declarations, ts.isInterfaceDeclaration); + if (classOrInterface) { + var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); + var declSourceFile = classOrInterface.getSourceFile(); + var inJs = ts.isSourceFileJavaScript(declSourceFile); + var call = ts.tryCast(parent.parent, ts.isCallExpression); + return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; + } + var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); + if (enumDeclaration) { + return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration }; + } + return undefined; + } + function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { - if (classDeclaration.kind === 205 /* ClassExpression */) { + if (classDeclaration.kind === 207 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); - changeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization); + changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization); } else { var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); @@ -103234,32 +107181,32 @@ var ts; return; } var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); - changeTracker.insertNodeAtConstructorEnd(classDeclarationSourceFile, classConstructor, propertyInitialization); + changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization); } } function initializePropertyToUndefined(obj, propertyName) { return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); } - function getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic) { + function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) { var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); - var addProp = createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, token.text, typeNode); - return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, token.text, typeNode)]; + var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)]; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 200 /* BinaryExpression */) { + if (token.parent.parent.kind === 202 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); // TODO: GH#18217 + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); } - function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } - function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, @@ -103267,10 +107214,10 @@ var ts; /*initializer*/ undefined); var lastProp = getNodeToInsertPropertyAfter(classDeclaration); if (lastProp) { - changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + changeTracker.insertNodeAfter(declSourceFile, lastProp, property); } else { - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property); } } // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. @@ -103284,7 +107231,7 @@ var ts; } return res; } - function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { + function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. var stringTypeNode = ts.createKeywordTypeNode(137 /* StringKeyword */); var indexingParameter = ts.createParameter( @@ -103296,24 +107243,37 @@ var ts; var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic, preferences); + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); - if (containingMethodDeclaration && containingMethodDeclaration.parent === classDeclaration) { - changeTracker.insertNodeAfter(classDeclarationSourceFile, containingMethodDeclaration, methodDeclaration); + if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { + changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); } else { - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); + changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); } } + function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { + /** + * create initializer only literal enum that has string initializer. + * value of initializer is a string literal that equal to name of enum member. + * numeric enum or empty enum will not create initializer. + */ + var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { + var type = checker.getTypeAtLocation(member); + return !!(type && type.flags & 68 /* StringLike */); + }); + var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); + changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -103347,7 +107307,7 @@ var ts; return { type: "install package", file: fileName, packageName: packageName }; } function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { - var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; var packageName = ts.getPackageName(moduleName).packageName; return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) @@ -103388,11 +107348,11 @@ var ts; function getClass(sourceFile, pos) { // Token is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); return ts.cast(token.parent, ts.isClassLike); } function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { - var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); + var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. @@ -103442,10 +107402,10 @@ var ts; }); function doChange(changes, sourceFile, constructor, superCall) { changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); - changes.deleteNode(sourceFile, superCall); + changes.delete(sourceFile, superCall); } function getNodes(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); if (token.kind !== 99 /* ThisKeyword */) return undefined; var constructor = ts.getContainingFunction(token); @@ -103484,7 +107444,7 @@ var ts; }); }, }); function getNode(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); return token.parent; } @@ -103520,7 +107480,7 @@ var ts; }); }, }); function getNodes(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); var heritageClauses = ts.getContainingClass(token).heritageClauses; var extendsToken = heritageClauses[0].getFirstToken(); return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; @@ -103576,7 +107536,7 @@ var ts; }); }, }); function getInfo(sourceFile, pos, diagCode) { - var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var node = ts.getTokenAtPosition(sourceFile, pos); if (!ts.isIdentifier(node)) return undefined; return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined }; @@ -103597,6 +107557,7 @@ var ts; var fixName = "unusedIdentifier"; var fixIdPrefix = "unusedIdentifier_prefix"; var fixIdDelete = "unusedIdentifier_delete"; + var fixIdInfer = "unusedIdentifier_infer"; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics._0_is_declared_but_never_used.code, @@ -103604,31 +107565,51 @@ var ts; ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ts.Diagnostics.All_destructured_elements_are_unused.code, ts.Diagnostics.All_variables_are_unused.code, + ts.Diagnostics.All_type_parameters_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program; var checker = program.getTypeChecker(); - var startToken = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var importDecl = tryGetFullImport(startToken); + var sourceFiles = program.getSourceFiles(); + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (ts.isJSDocTemplateTag(token)) { + return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; + } + if (token.kind === 27 /* LessThanToken */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); + return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; + } + var importDecl = tryGetFullImport(token); if (importDecl) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); - return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); + return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])]; } - var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, startToken, /*deleted*/ undefined, checker, /*isFixAll*/ false); }); + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); + }); if (delDestructure.length) { - return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)]; } - var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(t, sourceFile, startToken, /*deleted*/ undefined); }); + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); if (delVar.length) { - return [codefix.createCodeFixAction(fixName, delVar, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; } - var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined, checker, /*isFixAll*/ false); }); - if (deletion.length) { - result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); + if (token.kind === 126 /* InferKeyword */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); + var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; + result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); + } + else { + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); + if (deletion.length) { + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + } } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { @@ -103636,32 +107617,39 @@ var ts; } return result; }, - fixIds: [fixIdPrefix, fixIdDelete], + fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer], getAllCodeActions: function (context) { - // Track a set of deleted nodes that may be ancestors of other marked for deletion -- only delete the ancestors. - var deleted = new ts.NodeSet(); var sourceFile = context.sourceFile, program = context.program; var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var startToken = ts.getTokenAtPosition(sourceFile, diag.start, /*includeJsDocComment*/ false); - var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); + var token = ts.getTokenAtPosition(sourceFile, diag.start); switch (context.fixId) { case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); - } + tryPrefixDeclaration(changes, diag.code, sourceFile, token); break; - case fixIdDelete: - // Ignore if this range was already deleted. - if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); })) - break; - var importDecl = tryGetFullImport(startToken); + case fixIdDelete: { + if (token.kind === 126 /* InferKeyword */) + break; // Can't delete + var importDecl = tryGetFullImport(token); if (importDecl) { - changes.deleteNode(sourceFile, importDecl); + changes.delete(sourceFile, importDecl); + } + else if (ts.isJSDocTemplateTag(token)) { + changes.delete(sourceFile, token); } - else if (!tryDeleteFullDestructure(changes, sourceFile, startToken, deleted, checker, /*isFixAll*/ true) && - !tryDeleteFullVariableStatement(changes, sourceFile, startToken, deleted)) { - tryDeleteDeclaration(changes, sourceFile, token, deleted, checker, /*isFixAll*/ true); + else if (token.kind === 27 /* LessThanToken */) { + deleteTypeParameters(changes, sourceFile, token); + } + else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && + !tryDeleteFullVariableStatement(sourceFile, token, changes)) { + tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); + } + break; + } + case fixIdInfer: + if (token.kind === 126 /* InferKeyword */) { + changeInferToUnknown(changes, sourceFile, token); } break; default: @@ -103670,263 +107658,110 @@ var ts; }); }, }); + function changeInferToUnknown(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(142 /* UnknownKeyword */)); + } + function createDeleteFix(changes, diag) { + return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); + } + function deleteTypeParameters(changes, sourceFile, token) { + changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters)); + } // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. - function tryGetFullImport(startToken) { - return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; + function tryGetFullImport(token) { + return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; } - function tryDeleteFullDestructure(changes, sourceFile, startToken, deletedAncestors, checker, isFixAll) { - if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent)) + function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + if (token.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) return false; - var decl = ts.cast(startToken.parent, ts.isObjectBindingPattern).parent; - switch (decl.kind) { - case 232 /* VariableDeclaration */: - tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors); - break; - case 149 /* Parameter */: - if (!mayDeleteParameter(decl, checker, isFixAll)) - break; - if (deletedAncestors) - deletedAncestors.add(decl); - changes.deleteNodeInList(sourceFile, decl); - break; - case 182 /* BindingElement */: - if (deletedAncestors) - deletedAncestors.add(decl); - changes.deleteNode(sourceFile, decl); - break; - default: - return ts.Debug.assertNever(decl); + var decl = token.parent.parent; + if (decl.kind === 149 /* Parameter */) { + tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, decl); } return true; } - function tryDeleteFullVariableStatement(changes, sourceFile, startToken, deletedAncestors) { - var declarationList = ts.tryCast(startToken.parent, ts.isVariableDeclarationList); - if (declarationList && declarationList.getChildren(sourceFile)[0] === startToken) { - if (deletedAncestors) - deletedAncestors.add(declarationList); - changes.deleteNode(sourceFile, declarationList.parent.kind === 214 /* VariableStatement */ ? declarationList.parent : declarationList); + function tryDeleteFullVariableStatement(sourceFile, token, changes) { + var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { + changes.delete(sourceFile, declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList); return true; } return false; } - function getToken(sourceFile, pos) { - var token = ts.findPrecedingToken(pos, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); - // this handles var ["computed"] = 12; - return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token; - } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { // Don't offer to prefix a property. - if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) { + if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) + return; + if (token.kind === 126 /* InferKeyword */) { + token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; + } + if (ts.isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); } } function canPrefix(token) { switch (token.parent.kind) { case 149 /* Parameter */: + case 148 /* TypeParameter */: return true; - case 232 /* VariableDeclaration */: { + case 235 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 222 /* ForOfStatement */: - case 221 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 224 /* ForInStatement */: return true; } } } return false; } - function tryDeleteDeclaration(changes, sourceFile, token, deletedAncestors, checker, isFixAll) { - tryDeleteDeclarationWorker(changes, sourceFile, token, deletedAncestors, checker, isFixAll); + function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) { + tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll); if (ts.isIdentifier(token)) deleteAssignments(changes, sourceFile, token, checker); } function deleteAssignments(changes, sourceFile, token, checker) { ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { - if (ref.parent.kind === 185 /* PropertyAccessExpression */) + if (ref.parent.kind === 187 /* PropertyAccessExpression */) ref = ref.parent; - if (ref.parent.kind === 200 /* BinaryExpression */ && ref.parent.parent.kind === 216 /* ExpressionStatement */) { - changes.deleteNode(sourceFile, ref.parent.parent); + if (ref.parent.kind === 202 /* BinaryExpression */ && ref.parent.parent.kind === 219 /* ExpressionStatement */) { + changes.delete(sourceFile, ref.parent.parent); } }); } - function tryDeleteDeclarationWorker(changes, sourceFile, token, deletedAncestors, checker, isFixAll) { + function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) { var parent = token.parent; - switch (parent.kind) { - case 232 /* VariableDeclaration */: - tryDeleteVariableDeclaration(changes, sourceFile, parent, deletedAncestors); - break; - case 148 /* TypeParameter */: - var typeParameters = ts.getEffectiveTypeParameterDeclarations(parent.parent); - if (typeParameters.length === 1) { - var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; - var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1, /*includeJsDocComment*/ false); - var nextToken = ts.getTokenAtPosition(sourceFile, end, /*includeJsDocComment*/ false); - ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); - ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); - changes.deleteNodeRange(sourceFile, previousToken, nextToken); - } - else { - changes.deleteNodeInList(sourceFile, parent); - } - break; - case 149 /* Parameter */: - if (!mayDeleteParameter(parent, checker, isFixAll)) - break; - var oldFunction = parent.parent; - if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { - // Lambdas with exactly one parameter are special because, after removal, there - // must be an empty parameter list (i.e. `()`) and this won't necessarily be the - // case if the parameter is simply removed (e.g. in `x => 1`). - var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, // TODO: GH#18217 - oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); - // Drop leading and trailing trivia of the new function because we're only going - // to replace the span (vs the full span) of the old function - the old leading - // and trailing trivia will remain. - ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction); - } - else { - changes.deleteNodeInList(sourceFile, parent); - } - break; - case 182 /* BindingElement */: { - var pattern = parent.parent; - var preserveComma = pattern.kind === 181 /* ArrayBindingPattern */ && parent !== ts.last(pattern.elements); - if (preserveComma) { - changes.deleteNode(sourceFile, parent); - } - else { - changes.deleteNodeInList(sourceFile, parent); - } - break; - } - // handle case where 'import a = A;' - case 243 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 243 /* ImportEqualsDeclaration */); - changes.deleteNode(sourceFile, importEquals); - break; - case 248 /* ImportSpecifier */: - var namedImports = parent.parent; - if (namedImports.elements.length === 1) { - tryDeleteNamedImportBinding(changes, sourceFile, namedImports); - } - else { - // delete import specifier - changes.deleteNodeInList(sourceFile, parent); - } - break; - case 245 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *' - var importClause = parent; - if (!importClause.namedBindings) { // |import d from './file'| - changes.deleteNode(sourceFile, ts.getAncestor(importClause, 244 /* ImportDeclaration */)); - } - else { - // import |d,| * as ns from './file' - var start = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); - changes.deleteRange(sourceFile, { pos: start, end: end }); - } - else { - changes.deleteNode(sourceFile, importClause.name); - } - } - break; - case 246 /* NamespaceImport */: - tryDeleteNamedImportBinding(changes, sourceFile, parent); - break; - default: - if (ts.isDeclarationName(token)) { - if (deletedAncestors) - deletedAncestors.add(token.parent); - changes.deleteNode(sourceFile, token.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - if (deletedAncestors) - deletedAncestors.add(token.parent.parent); - changes.deleteNode(sourceFile, token.parent.parent); - } - break; - } - } - function tryDeleteNamedImportBinding(changes, sourceFile, namedBindings) { - if (namedBindings.parent.name) { - // Delete named imports while preserving the default import - // import d|, * as ns| from './file' - // import d|, { a }| from './file' - var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - changes.deleteRange(sourceFile, { pos: previousToken.getStart(), end: namedBindings.end }); - } + if (ts.isParameter(parent)) { + tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll); } else { - // Delete the entire import declaration - // |import * as ns from './file'| - // |import { a } from './file'| - var importDecl = ts.getAncestor(namedBindings, 244 /* ImportDeclaration */); - changes.deleteNode(sourceFile, importDecl); - } - } - // token.parent is a variableDeclaration - function tryDeleteVariableDeclaration(changes, sourceFile, varDecl, deletedAncestors) { - switch (varDecl.parent.parent.kind) { - case 220 /* ForStatement */: { - var forStatement = varDecl.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - if (deletedAncestors) - deletedAncestors.add(forInitializer); - changes.deleteNode(sourceFile, forInitializer); - } - else { - if (deletedAncestors) - deletedAncestors.add(varDecl); - changes.deleteNodeInList(sourceFile, varDecl); - } - break; - } - case 222 /* ForOfStatement */: - var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 233 /* VariableDeclarationList */); - var forOfInitializer = forOfStatement.initializer; - if (deletedAncestors) - deletedAncestors.add(forOfInitializer.declarations[0]); - changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); - break; - case 221 /* ForInStatement */: - case 230 /* TryStatement */: - break; - default: - var variableStatement = varDecl.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - if (deletedAncestors) - deletedAncestors.add(variableStatement); - changes.deleteNode(sourceFile, variableStatement); - } - else { - if (deletedAncestors) - deletedAncestors.add(varDecl); - changes.deleteNodeInList(sourceFile, varDecl); - } + changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); + } + } + function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { + if (mayDeleteParameter(p, checker, isFixAll)) { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); } } function mayDeleteParameter(p, checker, isFixAll) { var parent = p.parent; switch (parent.kind) { case 154 /* MethodDeclaration */: - // Don't remove a parameter if this overrides something + // Don't remove a parameter if this overrides something. var symbol = checker.getSymbolAtLocation(parent.name); if (ts.isMemberSymbolInBaseType(symbol, checker)) return false; // falls through case 155 /* Constructor */: - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: { - // Can't remove a non-last parameter. Can remove a parameter in code-fix-all if future parameters are also unused. + case 237 /* FunctionDeclaration */: + return true; + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: { + // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. var parameters = parent.parameters; var index = parameters.indexOf(p); ts.Debug.assert(index !== -1); @@ -103941,6 +107776,14 @@ var ts; return ts.Debug.failBadSyntaxKind(parent); } } + function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) { + ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) { + var index = deletedParameter.parent.parameters.indexOf(deletedParameter); + if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments. + changes.delete(sourceFile, call.arguments[index]); + } + }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -103953,69 +107796,54 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, }); - function doChange(changes, sourceFile, start) { - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + function doChange(changes, sourceFile, start, length) { + var token = ts.getTokenAtPosition(sourceFile, start); var statement = ts.findAncestor(token, ts.isStatement); ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; - switch (container.kind) { - case 217 /* IfStatement */: - if (container.elseStatement) { - if (ts.isBlock(statement.parent)) { - changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); - } - else { - changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 220 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; } - break; - } - // falls through - case 219 /* WhileStatement */: - case 220 /* ForStatement */: - changes.deleteNode(sourceFile, container); - break; - default: - if (ts.isBlock(statement.parent)) { - split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); - } - else { - changes.deleteNode(sourceFile, statement); - } + // falls through + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } } - } - function shouldRemove(s) { - // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && - // `var x;` may declare a variable used above - !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); - } - function isPurelyTypeDeclaration(s) { - switch (s.kind) { - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: - return true; - case 239 /* ModuleDeclaration */: - return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; - case 238 /* EnumDeclaration */: - return ts.hasModifier(s, 2048 /* Const */); - default: - return false; + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); } } - function sliceAfter(arr, value) { - var index = arr.indexOf(value); - ts.Debug.assert(index !== -1); - return arr.slice(index); - } - // Calls 'cb' with the start and end of each range where 'pred' is true. - function split(arr, pred, cb) { - ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); }); + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -104036,7 +107864,7 @@ var ts; getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, }); function doChange(changes, sourceFile, start) { - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, start); var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); var pos = token.getStart(sourceFile); var statementPos = labeledStatement.statement.getStart(sourceFile); @@ -104066,7 +107894,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 281 /* JSDocNullableType */) { + if (typeNode.kind === 284 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 8192 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -104086,7 +107914,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 281 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type; + var fixedType = typeNode.kind === 284 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -104095,7 +107923,7 @@ var ts; changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { - var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); var typeNode = decl && decl.type; return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; } @@ -104103,22 +107931,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 208 /* AsExpression */: + case 210 /* AsExpression */: case 158 /* CallSignature */: case 159 /* ConstructSignature */: - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: case 156 /* GetAccessor */: case 160 /* IndexSignature */: - case 177 /* MappedType */: + case 179 /* MappedType */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 149 /* Parameter */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: case 157 /* SetAccessor */: - case 237 /* TypeAliasDeclaration */: - case 190 /* TypeAssertionExpression */: - case 232 /* VariableDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 192 /* TypeAssertionExpression */: + case 235 /* VariableDeclaration */: return true; default: return false; @@ -104165,7 +107993,7 @@ var ts; } } function getNodes(sourceFile, start) { - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, start); var containingFunction = ts.getContainingFunction(token); if (!containingFunction) { return; @@ -104175,11 +108003,11 @@ var ts; case 154 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); break; - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: @@ -104316,8 +108144,8 @@ var ts; outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } - for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { - var signature = signatures_1[_i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var signature = signatures_8[_i]; // Need to ensure nodes are fresh each time so they can have different positions. outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); } @@ -104349,8 +108177,22 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(_a, methodName, inJs, makeStatic, preferences) { + function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + var checker = context.program.getTypeChecker(); + var types = ts.map(args, function (arg) { + var type = checker.getTypeAtLocation(arg); + if (type === undefined) { + return undefined; + } + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + type = checker.getBaseTypeOfLiteralType(type); + return checker.typeToTypeNode(type); + }); + var names = ts.map(args, function (arg) { + return ts.isIdentifier(arg) ? arg.text : + ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; + }); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -104359,11 +108201,11 @@ var ts; /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), - /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences)); + /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; - function createDummyParameters(argCount, names, minArgumentCount, inJs) { + function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { var newParameter = ts.createParameter( @@ -104372,7 +108214,7 @@ var ts; /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(119 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -104386,8 +108228,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { - var sig = signatures_2[_i]; + for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { + var sig = signatures_9[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -104398,7 +108240,7 @@ var ts; } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); - var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*inJs*/ false); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); var restParameter = ts.createParameter( @@ -104462,18 +108304,19 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { return undefined; // TODO: GH#20113 } - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, start); var declaration; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); - return changes.length === 0 ? undefined - : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); }); }, }); @@ -104555,11 +108398,11 @@ var ts; } function isApplicableFunctionForInference(declaration) { switch (declaration.kind) { - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 155 /* Constructor */: return true; - case 192 /* FunctionExpression */: + case 194 /* FunctionExpression */: return !!declaration.name; } return false; @@ -104619,8 +108462,8 @@ var ts; function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { switch (containingFunction.kind) { case 155 /* Constructor */: - case 192 /* FunctionExpression */: - case 234 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: var isConstructor = containingFunction.kind === 155 /* Constructor */; var searchToken = isConstructor ? @@ -104688,21 +108531,21 @@ var ts; node = node.parent; } switch (node.parent.kind) { - case 199 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: usageContext.isNumber = true; break; - case 198 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); break; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); break; - case 266 /* CaseClause */: - case 267 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); break; - case 187 /* CallExpression */: - case 188 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: if (node.parent.expression === node) { inferTypeFromCallExpressionContext(node.parent, checker, usageContext); } @@ -104710,13 +108553,13 @@ var ts; inferTypeFromContextualType(node, checker, usageContext); } break; - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); break; - case 186 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); break; - case 232 /* VariableDeclaration */: { + case 235 /* VariableDeclaration */: { var _a = node.parent, name = _a.name, initializer = _a.initializer; if (node === name) { if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. @@ -104825,7 +108668,7 @@ var ts; // LogicalOperator case 54 /* BarBarToken */: if (node === parent.left && - (node.parent.parent.kind === 232 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + (node.parent.parent.kind === 235 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); @@ -104853,7 +108696,7 @@ var ts; } } inferTypeFromContext(parent, checker, callContext.returnType); - if (parent.kind === 187 /* CallExpression */) { + if (parent.kind === 189 /* CallExpression */) { (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); } else { @@ -104875,7 +108718,7 @@ var ts; return; } else { - var indexType = checker.getTypeAtLocation(parent); + var indexType = checker.getTypeAtLocation(parent.argumentExpression); var indexUsageContext = {}; inferTypeFromContext(parent, checker, indexUsageContext); if (indexType.flags & 168 /* NumberLike */) { @@ -104908,7 +108751,7 @@ var ts; return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { - var members_1 = ts.createUnderscoreEscapedMap(); + var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; @@ -104917,7 +108760,7 @@ var ts; usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); - members_1.set(name, symbol); + members_6.set(name, symbol); }); } if (usageContext.callContexts) { @@ -104933,12 +108776,12 @@ var ts; } } if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); // TODO: GH#18217 + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 } else { return undefined; @@ -104993,22 +108836,6 @@ var ts; var codefix; (function (codefix) { var fixName = "invalidImportSyntax"; - codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], - getCodeActions: getActionsForInvalidImport - }); - function getActionsForInvalidImport(context) { - var sourceFile = context.sourceFile; - // This is the whole import statement, eg: - // import * as Bluebird from 'bluebird'; - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent; - if (!ts.isImportDeclaration(node)) { - // No import quick fix for import calls - return []; - } - return getCodeFixesForImportDeclaration(context, node); - } function getCodeFixesForImportDeclaration(context, node) { var sourceFile = ts.getSourceFileOfNode(node); var namespace = ts.getNamespaceDeclarationNode(node); @@ -105026,7 +108853,7 @@ var ts; } function createAction(context, sourceFile, node, replacement) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); - return codefix.createCodeFixActionNoFixId("invalidImportSyntax", changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -105037,13 +108864,42 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 187 /* CallExpression */ : 188 /* NewExpression */; - var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 189 /* CallExpression */ : 190 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); if (!node) { return []; } var expr = node.expression; - var type = context.program.getTypeChecker().getTypeAtLocation(expr); // TODO: GH#18217 + return getImportCodeFixesForExpression(context, expr); + } + codefix.registerCodeFix({ + errorCodes: [ + // The following error codes cover pretty much all assignability errors that could involve an expression + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code, + ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, + ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code, + ], + getCodeActions: getActionsForInvalidImportLocation + }); + function getActionsForInvalidImportLocation(context) { + var sourceFile = context.sourceFile; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + return getImportCodeFixesForExpression(context, node); + } + function getImportCodeFixesForExpression(context, expr) { + var type = context.program.getTypeChecker().getTypeAtLocation(expr); if (!(type.symbol && type.symbol.originatingImport)) { return []; } @@ -105052,8 +108908,11 @@ var ts; if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }); - fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { + var sourceFile_3 = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + } return fixes; } })(codefix = ts.codefix || (ts.codefix = {})); @@ -105108,7 +108967,7 @@ var ts; }, }); function getPropertyDeclaration(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; } function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { @@ -105193,7 +109052,7 @@ var ts; : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required))); } function getInfo(sourceFile, pos) { - var parent = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false).parent; + var parent = ts.getTokenAtPosition(sourceFile, pos).parent; if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true)) throw ts.Debug.failBadSyntaxKind(parent); var decl = ts.cast(parent.parent, ts.isVariableDeclaration); @@ -105226,7 +109085,7 @@ var ts; }); }, }); function getInfo(sourceFile, pos) { - var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var name = ts.getTokenAtPosition(sourceFile, pos); if (!ts.isIdentifier(name)) return undefined; // bad input var parent = name.parent; @@ -105250,7 +109109,7 @@ var ts; (function (codefix) { var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; var fixId = fixIdAddMissingTypeof; - var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here.code]; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { @@ -105265,9 +109124,9 @@ var ts; }); }, }); function getImportTypeNode(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); ts.Debug.assert(token.kind === 91 /* ImportKeyword */); - ts.Debug.assert(token.parent.kind === 179 /* ImportType */); + ts.Debug.assert(token.parent.kind === 181 /* ImportType */); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -105303,7 +109162,7 @@ var ts; }); } }); function getInfo(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); if (ts.isClassDeclaration(indexSignature.parent)) return undefined; @@ -105332,129 +109191,325 @@ var ts; (function (ts) { var refactor; (function (refactor) { - var generateGetAccessorAndSetAccessor; - (function (generateGetAccessorAndSetAccessor) { - var refactorName = "Convert import"; - var actionNameNamespaceToNamed = "Convert namespace import to named imports"; - var actionNameNamedToNamespace = "Convert named imports to namespace import"; - refactor.registerRefactor(refactorName, { - getAvailableActions: function (context) { - var i = getImportToConvert(context); - if (!i) + var refactorName = "Convert export"; + var actionNameDefaultToNamed = "Convert default export to named export"; + var actionNameNamedToDefault = "Convert named export to default export"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var info = getInfo(context); + if (!info) + return undefined; + var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; + var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context)), t, context.cancellationToken); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + }, + }); + function getInfo(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var exportNode = ts.getParentNodeInSpan(token, file, span); + if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { + return undefined; + } + var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var flags = ts.getModifierFlags(exportNode); + var wasDefault = !!(flags & 512 /* Default */); + // If source file already has a default export, don't offer refactor. + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return undefined; + } + switch (exportNode.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 242 /* ModuleDeclaration */: { + var node = exportNode; + return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + case 217 /* VariableStatement */: { + var vs = exportNode; + // Must be `export const x = something;`. + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { return undefined; - var description = i.kind === 246 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; - var actionName = i.kind === 246 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; - return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; - }, - getEditsForAction: function (context, actionName) { - ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); }); - return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + var decl = ts.first(vs.declarationList.declarations); + if (!decl.initializer) + return undefined; + ts.Debug.assert(!wasDefault); + return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } - }); - // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. - function getImportToConvert(context) { - var file = context.file; - var span = ts.getRefactorContextSpan(context); - var token = ts.getTokenAtPosition(file, span.start, /*includeJsDocComment*/ false); - var importDecl = ts.getParentNodeInSpan(token, file, span); - if (!importDecl || !ts.isImportDeclaration(importDecl)) + default: return undefined; - var importClause = importDecl.importClause; - return importClause && importClause.namedBindings; } - function doChange(sourceFile, program, changes, toConvert) { - var checker = program.getTypeChecker(); - if (toConvert.kind === 246 /* NamespaceImport */) { - doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); + } + function changeExport(exportingSourceFile, _a, changes, checker) { + var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; + if (wasDefault) { + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 79 /* DefaultKeyword */))); + } + else { + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* ExportKeyword */)); + switch (exportNode.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(79 /* DefaultKeyword */)); + break; + case 217 /* VariableStatement */: + // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` + if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { + // We checked in `getInfo` that an initializer exists. + changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer))); + break; + } + // falls through + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 242 /* ModuleDeclaration */: + // `export type T = number;` -> `type T = number; export default T;` + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); + break; + default: + ts.Debug.assertNever(exportNode); + } + } + } + function changeImports(program, _a, changes, cancellationToken) { + var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol; + var checker = program.getTypeChecker(); + var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName)); + ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + var importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); } else { - doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + changeNamedToDefaultImport(importingSourceFile, ref, changes); } - } - function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { - var usedAsNamespaceOrDefault = false; - var nodesToReplace = []; - var conflictingNames = ts.createMap(); - ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) { - if (!ts.isPropertyAccessExpression(id.parent)) { - usedAsNamespaceOrDefault = true; + }); + } + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + var parent = ref.parent; + switch (parent.kind) { + case 187 /* PropertyAccessExpression */: + // `a.default` --> `a.foo` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); + break; + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: { + var spec = parent; + // `default as foo` --> `foo`, `default as bar` --> `foo as bar` + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 248 /* ImportClause */: { + var clause = parent; + ts.Debug.assert(clause.name === ref); + var spec = makeImportSpecifier(exportName, ref.text); + var namedBindings = clause.namedBindings; + if (!namedBindings) { + // `import foo from "./a";` --> `import { foo } from "./a";` + changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); + } + else if (namedBindings.kind === 249 /* NamespaceImport */) { + // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); } else { - var parent = ts.cast(id.parent, ts.isPropertyAccessExpression); - var exportName = parent.name.text; - if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) { - conflictingNames.set(exportName, true); - } - ts.Debug.assert(parent.expression === id); - nodesToReplace.push(parent); + // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";` + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); } - }); - // We may need to change `mod.x` to `_x` to avoid a name conflict. - var exportNameToImportName = ts.createMap(); - for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) { - var propertyAccess = nodesToReplace_1[_i]; - var exportName = propertyAccess.name.text; - var importName = exportNameToImportName.get(exportName); - if (importName === undefined) { - exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName); - } - changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName)); - } - var importSpecifiers = []; - exportNameToImportName.forEach(function (name, propertyName) { - importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name))); - }); - var importDecl = toConvert.parent.parent; - if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { - // Need to leave the namespace import alone - changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers)); - } - else { - changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers)); + break; } + default: + ts.Debug.failBadSyntaxKind(parent); } - function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { - var importDecl = toConvert.parent.parent; - var moduleSpecifier = importDecl.moduleSpecifier; - var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module"; - var namespaceNameConflicts = toConvert.elements.some(function (element) { - return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { - return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true); - }) || false; - }); - var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; - var neededNamedImports = []; - var _loop_11 = function (element) { - var propertyName = (element.propertyName || element.name).text; - ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { - var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); - if (ts.isShorthandPropertyAssignment(id.parent)) { - changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access)); - } - else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) { - if (!neededNamedImports.some(function (n) { return n.name === element.name; })) { - neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text))); - } + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + var parent = ref.parent; + switch (parent.kind) { + case 187 /* PropertyAccessExpression */: + // `a.foo` --> `a.default` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); + break; + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: { + var spec = parent; + if (spec.kind === 251 /* ImportSpecifier */) { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(spec.name.text); + if (spec.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, spec.parent, defaultImport); } else { - changes.replaceNode(sourceFile, id, access); + changes.delete(importingSourceFile, spec); + changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport); } - }); - }; - for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { - var element = _a[_i]; - _loop_11(element); + } + else { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text)); + } + break; + } + default: + ts.Debug.failBadSyntaxKind(parent); + } + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + function makeExportSpecifier(propertyName, name) { + return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert import"; + var actionNameNamespaceToNamed = "Convert namespace import to named imports"; + var actionNameNamedToNamespace = "Convert named imports to namespace import"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var i = getImportToConvert(context); + if (!i) + return undefined; + var description = i.kind === 249 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 249 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. + function getImportToConvert(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var importDecl = ts.getParentNodeInSpan(token, file, span); + if (!importDecl || !ts.isImportDeclaration(importDecl)) + return undefined; + var importClause = importDecl.importClause; + return importClause && importClause.namedBindings; + } + function doChange(sourceFile, program, changes, toConvert) { + var checker = program.getTypeChecker(); + if (toConvert.kind === 249 /* NamespaceImport */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } + else { + doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + } + } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + var usedAsNamespaceOrDefault = false; + var nodesToReplace = []; + var conflictingNames = ts.createMap(); + ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) { + if (!ts.isPropertyAccessExpression(id.parent)) { + usedAsNamespaceOrDefault = true; } - changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); - if (neededNamedImports.length) { - changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports)); + else { + var parent = ts.cast(id.parent, ts.isPropertyAccessExpression); + var exportName = parent.name.text; + if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) { + conflictingNames.set(exportName, true); + } + ts.Debug.assert(parent.expression === id); + nodesToReplace.push(parent); } + }); + // We may need to change `mod.x` to `_x` to avoid a name conflict. + var exportNameToImportName = ts.createMap(); + for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) { + var propertyAccess = nodesToReplace_1[_i]; + var exportName = propertyAccess.name.text; + var importName = exportNameToImportName.get(exportName); + if (importName === undefined) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName)); + } + var importSpecifiers = []; + exportNameToImportName.forEach(function (name, propertyName) { + importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name))); + }); + var importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + // Need to leave the namespace import alone + changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers)); } - function updateImport(old, defaultImportName, elements) { - return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier); + else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers)); } - })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); + } + function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { + var importDecl = toConvert.parent.parent; + var moduleSpecifier = importDecl.moduleSpecifier; + var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module"; + var namespaceNameConflicts = toConvert.elements.some(function (element) { + return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true); + }) || false; + }); + var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; + var neededNamedImports = []; + var _loop_22 = function (element) { + var propertyName = (element.propertyName || element.name).text; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); + if (ts.isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access)); + } + else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) { + if (!neededNamedImports.some(function (n) { return n.name === element.name; })) { + neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text))); + } + } + else { + changes.replaceNode(sourceFile, id, access); + } + }); + }; + for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { + var element = _a[_i]; + _loop_22(element); + } + changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); + if (neededNamedImports.length) { + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports)); + } + } + function updateImport(old, defaultImportName, elements) { + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier); + } })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ @@ -105612,7 +109667,7 @@ var ts; } // 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 = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false), sourceFile, span); + var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span); // Do the same for the ending position var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); var declarations = []; @@ -105765,7 +109820,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 232 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 235 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -105777,13 +109832,13 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; case 97 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 187 /* CallExpression */) { + if (node.parent.kind === 189 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -105798,8 +109853,8 @@ var ts; } if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 234 /* FunctionDeclaration */: - case 235 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); @@ -105811,20 +109866,20 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 217 /* IfStatement */: + case 220 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 230 /* TryStatement */: + case 233 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 213 /* Block */: - if (node.parent && node.parent.kind === 230 /* TryStatement */ && node.parent.finallyBlock === node) { + case 216 /* Block */: + if (node.parent && node.parent.kind === 233 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 266 /* CaseClause */: + case 269 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -105836,11 +109891,11 @@ var ts; break; } switch (node.kind) { - case 174 /* ThisType */: + case 176 /* ThisType */: case 99 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -105848,8 +109903,8 @@ var ts; seenLabels.pop(); break; } - case 224 /* BreakStatement */: - case 223 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: { var label = node.label; if (label) { @@ -105859,20 +109914,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 224 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 227 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 197 /* AwaitExpression */: + case 199 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 203 /* YieldExpression */: + case 205 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -105937,7 +109992,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 274 /* SourceFile */) { + if (current.kind === 277 /* SourceFile */) { return scopes; } } @@ -106029,12 +110084,12 @@ var ts; switch (scope.kind) { case 155 /* Constructor */: return "constructor"; - case 192 /* FunctionExpression */: - case 234 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : "anonymous function"; - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: return "arrow function"; case 154 /* MethodDeclaration */: return "method '" + scope.name.getText(); @@ -106047,12 +110102,12 @@ var ts; } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 235 /* ClassDeclaration */ + return scope.kind === 238 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 240 /* ModuleBlock */ + return scope.kind === 243 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -106179,8 +110234,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), // TODO: GH#18217 - scope, 1 /* NoTruncation */); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -106331,7 +110385,7 @@ var ts; var localReference = ts.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 216 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 219 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.createVariableStatement( @@ -106350,9 +110404,9 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 216 /* ExpressionStatement */) { + if (node.parent.kind === 219 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. - changeTracker.deleteNode(context.file, node.parent, ts.textChanges.useNonAdjustedPositions); + changeTracker.delete(context.file, node.parent); } else { var localReference = ts.createIdentifier(localNameText); @@ -106437,7 +110491,7 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 225 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + if (!ignoreReturns && node.kind === 228 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { @@ -106485,7 +110539,7 @@ var ts; return scope.members; } else { - ts.assertTypeIsNever(scope); + ts.assertType(scope); } return ts.emptyArray; } @@ -106503,8 +110557,8 @@ var ts; ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. var prevMember; var allProperties = true; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_7 = members; _i < members_7.length; _i++) { + var member = members_7[_i]; if (member.pos > maxPos) { return prevMember || members[0]; } @@ -106607,7 +110661,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { // TODO: GH#18217 + else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -106615,7 +110669,7 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 234 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 237 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; @@ -106678,7 +110732,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_12 = function (i) { + var _loop_23 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -106718,7 +110772,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_12(i); + _loop_23(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -106740,7 +110794,7 @@ var ts; function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1 /* Read */; } if (inGenericContext) { - var type = checker.getTypeAtLocation(node); // TODO: GH#18217 + var type = checker.getTypeAtLocation(node); recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { @@ -106931,30 +110985,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 273 /* EnumMember */: + case 276 /* EnumMember */: return false; } switch (node.kind) { case 9 /* StringLiteral */: - return parent.kind !== 244 /* ImportDeclaration */ && - parent.kind !== 248 /* ImportSpecifier */; - case 204 /* SpreadElement */: - case 180 /* ObjectBindingPattern */: - case 182 /* BindingElement */: + return parent.kind !== 247 /* ImportDeclaration */ && + parent.kind !== 251 /* ImportSpecifier */; + case 206 /* SpreadElement */: + case 182 /* ObjectBindingPattern */: + case 184 /* BindingElement */: return false; case 71 /* Identifier */: - return parent.kind !== 182 /* BindingElement */ && - parent.kind !== 248 /* ImportSpecifier */ && - parent.kind !== 252 /* ExportSpecifier */; + return parent.kind !== 184 /* BindingElement */ && + parent.kind !== 251 /* ImportSpecifier */ && + parent.kind !== 255 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 213 /* Block */: - case 274 /* SourceFile */: - case 240 /* ModuleBlock */: - case 266 /* CaseClause */: + case 216 /* Block */: + case 277 /* SourceFile */: + case 243 /* ModuleBlock */: + case 269 /* CaseClause */: return true; default: return false; @@ -106974,8 +111028,7 @@ var ts; var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { - var file = context.file; - if (!getConvertibleFieldAtPosition(context, file)) + if (!getConvertibleFieldAtPosition(context)) return undefined; return [{ name: actionName, @@ -106990,7 +111043,7 @@ var ts; } function getEditsForAction(context, _actionName) { var file = context.file; - var fieldInfo = getConvertibleFieldAtPosition(context, file); + var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; var isJS = ts.isSourceFileJavaScript(file); @@ -107051,13 +111104,13 @@ var ts; function startsWithUnderscore(name) { return name.charCodeAt(0) === 95 /* _ */; } - function getConvertibleFieldAtPosition(context, file) { - var startPosition = context.startPosition, endPosition = context.endPosition; - var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + function getConvertibleFieldAtPosition(context) { + var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition; + var node = ts.getTokenAtPosition(file, startPosition); var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; - if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) // TODO: GH#18217 + if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217 || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; var name = declaration.name.text; @@ -107212,11 +111265,11 @@ var ts; } function isPureImport(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return true; - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return !ts.hasModifier(node, 1 /* Export */); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -107246,7 +111299,7 @@ var ts; var quotePreference = ts.getQuotePreference(oldFile, preferences); var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); if (importsFromNewFile) { - changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true); + ts.insertImport(changes, oldFile, importsFromNewFile); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); @@ -107269,10 +111322,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_13 = function (sourceFile) { + var _loop_24 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_14 = function (statement) { + var _loop_25 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -107294,22 +111347,22 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_14(statement); + _loop_25(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_13(sourceFile); + _loop_24(sourceFile); } } function getNamespaceLikeImport(node) { switch (node.kind) { - case 244 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 246 /* NamespaceImport */ ? + case 247 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 249 /* NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return node.name; - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node); @@ -107340,20 +111393,20 @@ var ts; var newNamespaceId = ts.createIdentifier(newNamespaceName); var newModuleString = ts.createLiteral(newModuleSpecifier); switch (node.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node); } } function moduleSpecifierFromImport(i) { - return (i.kind === 244 /* ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 243 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 247 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 246 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -107414,24 +111467,24 @@ var ts; if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { - var exports = addExport(statement, useEs6Exports); - if (exports) - return exports; + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; } return statement; }); } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { - changes.deleteNode(sourceFile, importDecl); + changes.delete(sourceFile, importDecl); } break; - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -107444,23 +111497,23 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 246 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { - changes.deleteNode(sourceFile, importDecl); + changes.delete(sourceFile, importDecl); } else { if (name && defaultUnused) { - changes.deleteNode(sourceFile, name); + changes.delete(sourceFile, name); } if (namedBindings) { if (namedBindingsUnused) { - changes.deleteNode(sourceFile, namedBindings); + changes.delete(sourceFile, namedBindings); } - else if (namedBindings.kind === 247 /* NamedImports */) { + else if (namedBindings.kind === 250 /* NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) - changes.deleteNodeInList(sourceFile, element); + changes.delete(sourceFile, element); } } } @@ -107471,20 +111524,20 @@ var ts; switch (name.kind) { case 71 /* Identifier */: if (isUnused(name)) { - changes.deleteNode(sourceFile, name); + changes.delete(sourceFile, name); } break; - case 181 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: break; - case 180 /* ObjectBindingPattern */: + case 182 /* ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { - changes.deleteNode(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } else { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (ts.isIdentifier(element.name) && isUnused(element.name)) { - changes.deleteNode(sourceFile, element.name); + changes.delete(sourceFile, element.name); } } } @@ -107581,13 +111634,13 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 243 /* ImportEqualsDeclaration */: - case 248 /* ImportSpecifier */: - case 245 /* ImportClause */: + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 248 /* ImportClause */: return true; - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 182 /* BindingElement */: + case 184 /* BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -107599,7 +111652,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 244 /* ImportDeclaration */: { + case 247 /* ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -107609,9 +111662,9 @@ var ts; ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) : undefined; } - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 232 /* VariableDeclaration */: { + case 235 /* VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -107620,7 +111673,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 246 /* NamespaceImport */) { + if (namedBindings.kind === 249 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -107632,9 +111685,9 @@ var ts; switch (name.kind) { case 71 /* Identifier */: return keep(name) ? name : undefined; - case 181 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: return name; - case 180 /* ObjectBindingPattern */: { + case 182 /* ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; @@ -107691,13 +111744,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 234 /* FunctionDeclaration */: - case 235 /* ClassDeclaration */: - case 239 /* ModuleDeclaration */: - case 238 /* EnumDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 236 /* InterfaceDeclaration */: - case 243 /* ImportEqualsDeclaration */: + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 246 /* ImportEqualsDeclaration */: return true; default: return false; @@ -107705,17 +111758,17 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 234 /* FunctionDeclaration */: - case 235 /* ClassDeclaration */: - case 239 /* ModuleDeclaration */: - case 238 /* EnumDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 236 /* InterfaceDeclaration */: - case 243 /* ImportEqualsDeclaration */: + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 246 /* ImportEqualsDeclaration */: return cb(statement); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return ts.forEach(statement.declarationList.declarations, cb); - case 216 /* ExpressionStatement */: { + case 219 /* ExpressionStatement */: { var expression = statement.expression; return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ ? cb(statement) @@ -107724,7 +111777,7 @@ var ts; } } function nameOfTopLevelDeclaration(d) { - return d.kind === 216 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + return d.kind === 219 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); } function getTopLevelDeclarationStatement(d) { return ts.isVariableDeclaration(d) ? d.parent.parent : d; @@ -107756,23 +111809,23 @@ var ts; function addEs6Export(d) { var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); switch (d.kind) { - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return ts.updateVariableStatement(d, modifiers, d.declarationList); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); - case 237 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); - case 236 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d); @@ -107783,18 +111836,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 234 /* FunctionDeclaration */: - case 235 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 239 /* ModuleDeclaration */: - case 238 /* EnumDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 236 /* InterfaceDeclaration */: - case 243 /* ImportEqualsDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 246 /* ImportEqualsDeclaration */: return ts.emptyArray; - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl); @@ -107869,7 +111922,7 @@ var ts; return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */ || ts.isObjectLiteralExpression(expression); } function getConvertibleArrowFunctionAtPosition(file, startPosition) { - var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + var node = ts.getTokenAtPosition(file, startPosition); var func = ts.getContainingFunction(node); if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node))) return undefined; @@ -107896,250 +111949,6 @@ var ts; })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - var sourcemaps; - (function (sourcemaps) { - sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; - function decode(host, mapPath, map, program, fallbackCache) { - if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } - var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot || currentDirectory; - var decodedMappings; - var generatedOrderedMappings; - var sourceOrderedMappings; - return { - getOriginalPosition: getOriginalPosition, - getGeneratedPosition: getGeneratedPosition - }; - function getGeneratedPosition(loc) { - var maps = getGeneratedOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { - return loc; - } - return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos - } - function getOriginalPosition(loc) { - var maps = getSourceOrderedMappings(); - if (!ts.length(maps)) - return loc; - var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); - if (targetIndex < 0 && maps.length > 0) { - // if no exact match, closest is 2's compliment of result - targetIndex = ~targetIndex; - } - return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos - } - function getSourceFileLike(fileName, location) { - // Lookup file in program, if provided - var file = program && program.getSourceFile(fileName); - if (!file) { - // Otherwise check the cache (which may hit disk) - var path = ts.toPath(fileName, location, host.getCanonicalFileName); - return fallbackCache.get(path); - } - return file; - } - function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { - var file = getSourceFileLike(fileName, directory); - if (!file) { - return -1; - } - return ts.getPositionOfLineAndCharacter(file, line, character); - } - function getDecodedMappings() { - return decodedMappings || (decodedMappings = calculateDecodedMappings()); - } - function getSourceOrderedMappings() { - return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); - } - function getGeneratedOrderedMappings() { - return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); - } - function calculateDecodedMappings() { - var state = { - encodedText: map.mappings, - currentNameIndex: undefined, - sourceMapNamesLength: map.names ? map.names.length : undefined, - currentEmittedColumn: 0, - currentEmittedLine: 0, - currentSourceColumn: 0, - currentSourceLine: 0, - currentSourceIndex: 0, - positions: [], - decodingIndex: 0, - processPosition: processPosition, - }; - while (!hasCompletedDecoding(state)) { - decodeSinglePosition(state); - if (state.error) { - host.log("Encountered error while decoding sourcemap found at " + mapPath + ": " + state.error); - return []; - } - } - return state.positions; - } - function compareProcessedPositionSourcePositions(a, b) { - return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || - ts.compareValues(a.sourcePosition, b.sourcePosition); - } - function compareProcessedPositionEmittedPositions(a, b) { - return ts.compareValues(a.emittedPosition, b.emittedPosition); - } - function processPosition(position) { - var sourcePath = map.sources[position.sourceIndex]; - return { - emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), - sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), - sourcePath: sourcePath, - }; - } - } - sourcemaps.decode = decode; - function hasCompletedDecoding(state) { - return state.decodingIndex === state.encodedText.length; - } - function decodeSinglePosition(state) { - while (state.decodingIndex < state.encodedText.length) { - var char = state.encodedText.charCodeAt(state.decodingIndex); - if (char === 59 /* semicolon */) { - // New line - state.currentEmittedLine++; - state.currentEmittedColumn = 0; - state.decodingIndex++; - continue; - } - if (char === 44 /* comma */) { - // Next entry is on same line - no action needed - state.decodingIndex++; - continue; - } - // Read the current position - // 1. Column offset from prev read jsColumn - state.currentEmittedColumn += base64VLQFormatDecode(); - // Incorrect emittedColumn dont support this map - if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { - return; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { - return; - } - // 2. Relative sourceIndex - state.currentSourceIndex += base64VLQFormatDecode(); - // Incorrect sourceIndex dont support this map - if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { - return; - } - // Dont support reading mappings that dont have information about original source position - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { - return; - } - // 3. Relative sourceLine 0 based - state.currentSourceLine += base64VLQFormatDecode(); - // Incorrect sourceLine dont support this map - if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { - return; - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { - return; - } - // 4. Relative sourceColumn 0 based - state.currentSourceColumn += base64VLQFormatDecode(); - // Incorrect sourceColumn dont support this map - if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { - return; - } - // 5. Check if there is name: - if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { - if (state.currentNameIndex === undefined) { - state.currentNameIndex = 0; - } - state.currentNameIndex += base64VLQFormatDecode(); - // Incorrect nameIndex dont support this map - // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap - // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { - // return; - // } - } - // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { - return; - } - // Entry should be complete - capturePosition(); - return; - } - createErrorIfCondition(/*condition*/ true, "No encoded entry found"); - return; - function capturePosition() { - state.positions.push(state.processPosition({ - emittedColumn: state.currentEmittedColumn, - emittedLine: state.currentEmittedLine, - sourceColumn: state.currentSourceColumn, - sourceIndex: state.currentSourceIndex, - sourceLine: state.currentSourceLine, - nameIndex: state.currentNameIndex - })); - } - function createErrorIfCondition(condition, errormsg) { - if (state.error) { - // An error was already reported - return true; - } - if (condition) { - state.error = errormsg; - } - return condition; - } - function base64VLQFormatDecode() { - var moreDigits = true; - var shiftCount = 0; - var value = 0; - for (; moreDigits; state.decodingIndex++) { - if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { - return undefined; // TODO: GH#18217 - } - // 6 digit number - var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); - // If msb is set, we still have more bits to continue - moreDigits = (currentByte & 32) !== 0; - // least significant 5 bits are the next msbs in the final value. - value = value | ((currentByte & 31) << shiftCount); - shiftCount += 5; - } - // Least significant bit if 1 represents negative and rest of the msb is actual absolute value - if ((value & 1) === 0) { - // + number - value = value >> 1; - } - else { - // - number - value = value >> 1; - value = -value; - } - return value; - } - } - function base64FormatDecode(char) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); - } - function isSourceMappingSegmentEnd(encodedText, pos) { - return (pos === encodedText.length || - encodedText.charCodeAt(pos) === 44 /* comma */ || - encodedText.charCodeAt(pos) === 59 /* semicolon */); - } - })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); -})(ts || (ts = {})); var ts; (function (ts) { /** The version of the language service API */ @@ -108219,7 +112028,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 278 /* FirstJSDocNode */ || kid.kind > 298 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 303 /* LastJSDocNode */; }); return child.kind < 146 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -108289,11 +112098,11 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(299 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(304 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -108346,7 +112155,7 @@ var ts; return undefined; // TODO: GH#18217 }; TokenOrIdentifierObject.prototype.getChildren = function () { - return ts.emptyArray; + return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray; }; TokenOrIdentifierObject.prototype.getFirstToken = function () { return undefined; @@ -108535,8 +112344,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -108600,7 +112409,7 @@ var ts; }; SourceFileObject.prototype.computeNamedDeclarations = function () { var result = ts.createMultiMap(); - ts.forEachChild(this, visit); + this.forEachChild(visit); return result; function addDeclaration(declaration) { var name = getDeclarationName(declaration); @@ -108616,14 +112425,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - var name = ts.getNameOfDeclaration(declaration); + var name = ts.getNonAssignedNameOfDeclaration(declaration); return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined); } function visit(node) { switch (node.kind) { - case 234 /* FunctionDeclaration */: - case 192 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: var functionDeclaration = node; @@ -108645,17 +112454,17 @@ var ts; } ts.forEachChild(node, visit); break; - case 235 /* ClassDeclaration */: - case 205 /* ClassExpression */: - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: - case 238 /* EnumDeclaration */: - case 239 /* ModuleDeclaration */: - case 243 /* ImportEqualsDeclaration */: - case 252 /* ExportSpecifier */: - case 248 /* ImportSpecifier */: - case 245 /* ImportClause */: - case 246 /* NamespaceImport */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 255 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: case 166 /* TypeLiteral */: @@ -108668,8 +112477,8 @@ var ts; break; } // falls through - case 232 /* VariableDeclaration */: - case 182 /* BindingElement */: { + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -108680,31 +112489,31 @@ var ts; } } // falls through - case 273 /* EnumMember */: + case 276 /* EnumMember */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: addDeclaration(node); break; - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: // import d from "mod"; if (importClause.name) { - addDeclaration(importClause); + addDeclaration(importClause.name); } // Handle named bindings in imports e.g.: // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 246 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -108713,7 +112522,7 @@ var ts; } } break; - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { addDeclaration(node); } @@ -109005,31 +112814,6 @@ var ts; return ThrottledCancellationToken; }()); ts.ThrottledCancellationToken = ThrottledCancellationToken; - /* @internal */ - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); - return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); - } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); - } - }; - cached.set(path, file); - return file; - } - }; - } - ts.createSourceFileLikeCache = createSourceFileLikeCache; function createLanguageService(host, documentRegistry, syntaxOnly) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } if (syntaxOnly === void 0) { syntaxOnly = false; } @@ -109044,7 +112828,6 @@ var ts; if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } - var sourcemappedFileCache; function log(message) { if (host.log) { host.log(message); @@ -109052,6 +112835,7 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -109106,7 +112890,7 @@ var ts; readFile: function (fileName) { // stub missing host functionality var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache.getEntryByPath(path); + var entry = hostCache && hostCache.getEntryByPath(path); if (entry) { return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } @@ -109149,14 +112933,14 @@ var ts; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during // the course of whatever called `synchronizeHostData` - sourcemappedFileCache = createSourceFileLikeCache(host); + sourceMapper.clearCache(); // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); return; function fileExists(fileName) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache.getEntryByPath(path); + var entry = hostCache && hostCache.getEntryByPath(path); return entry ? !ts.isString(entry) : (!!host.fileExists && host.fileExists(fileName)); @@ -109171,11 +112955,11 @@ var ts; return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); } function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { - ts.Debug.assert(hostCache !== undefined); + ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. - var hostFileInformation = hostCache.getOrCreateEntryByPath(fileName, path); + var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); if (!hostFileInformation) { return undefined; } @@ -109271,17 +113055,17 @@ var ts; return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = ts.defaultPreferences; } + if (options === void 0) { options = ts.emptyOptions; } // Convert from deprecated options names to new names var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); } function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { - if (preferences === void 0) { preferences = ts.defaultPreferences; } + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 - getCanonicalFileName, preferences, cancellationToken); + preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -109298,31 +113082,15 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - // Try getting just type at this position and show - switch (node.kind) { - case 71 /* Identifier */: - if (ts.isLabelName(node)) { - // Type here will be 'any', avoid displaying this. - return undefined; - } - // falls through - case 185 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: - case 99 /* ThisKeyword */: - case 174 /* ThisType */: - case 97 /* SuperKeyword */: - // For the identifiers/this/super etc get the type at position - var type_1 = typeChecker.getTypeAtLocation(node); - return type_1 && { - kind: "" /* unknown */, - kindModifiers: "" /* none */, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_1, ts.getContainerNode(node)); }), - documentation: type_1.symbol ? type_1.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_1.symbol ? type_1.symbol.getJsDocTags() : undefined - }; - } - return undefined; + var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_4 && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), + documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); @@ -109336,172 +113104,39 @@ var ts; tags: 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); - var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); - if (property) { - return property; - } - } - return checker.getSymbolAtLocation(node); - } - function toLineColumnOffset(fileName, position) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 - return file.getLineAndCharacterOfPosition(position); - } - // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) - var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/gm; - var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); - if (!mappedFile) { - return; - } - var starts = ts.getLineStarts(mappedFile); - for (var index = starts.length - 1; index >= 0; index--) { - sourceMapCommentRegExp.lastIndex = starts[index]; - var comment = sourceMapCommentRegExp.exec(mappedFile.text); - if (comment) { - return comment[1]; - } - } - } - function convertDocumentToSourceMapper(file, contents, mapFileName) { - var maps; - try { - maps = JSON.parse(contents); - } - catch (_a) { - // swallow error - } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { - // obviously invalid map - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - return file.sourceMapper = ts.sourcemaps.decode({ - readFile: function (s) { return host.readFile(s); }, - fileExists: function (s) { return host.fileExists(s); }, - getCanonicalFileName: getCanonicalFileName, - log: log, - }, mapFileName, maps, program, sourcemappedFileCache); - } - function getSourceMapper(fileName, file) { - if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - if (file.sourceMapper) { - return file.sourceMapper; - } - var mapFileName = scanForSourcemapURL(fileName); - if (mapFileName) { - var match = base64UrlRegExp.exec(mapFileName); - if (match) { - if (match[1]) { - var base64Object = match[1]; - return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); - } - // Not a data URL we can parse, skip it - mapFileName = undefined; - } - } - var possibleMapLocations = []; - if (mapFileName) { - possibleMapLocations.push(mapFileName); - } - possibleMapLocations.push(fileName + ".map"); - for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { - var location = possibleMapLocations_1[_i]; - var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); - if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 - } - } - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - function makeGetTargetOfMappedPosition(extract, create) { - return getTargetOfMappedPosition; - function getTargetOfMappedPosition(input, original) { - if (original === void 0) { original = input; } - var info = extract(input); - if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { - var file = program.getSourceFile(info.fileName); - if (!file) { - var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); - file = sourcemappedFileCache.get(path); - } - if (!file) { - return input; - } - var mapper = getSourceMapper(info.fileName, file); - var newLoc = mapper.getOriginalPosition(info); - if (newLoc === info) - return input; - return getTargetOfMappedPosition(create(newLoc, input, original), original); - } - return input; + function shouldGetType(sourceFile, node, position) { + switch (node.kind) { + case 71 /* Identifier */: + return !ts.isLabelName(node); + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: + // Don't return quickInfo if inside the comment in `a/**/.b` + return !ts.isInComment(sourceFile, position); + case 99 /* ThisKeyword */: + case 176 /* ThisType */: + case 97 /* SuperKeyword */: + return true; + default: + return false; } } - var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({ - containerKind: info.containerKind, - containerName: info.containerName, - fileName: newLoc.fileName, - kind: info.kind, - name: info.name, - textSpan: { - start: newLoc.position, - length: info.textSpan.length - }, - originalFileName: original.fileName, - originalTextSpan: original.textSpan - }); }); - function getTargetOfMappedDeclarationFiles(infos) { - return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); }); - } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position)); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } function getDefinitionAndBoundSpan(fileName, position) { synchronizeHostData(); - var result = ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); - if (!result) - return result; - var mappedDefs = getTargetOfMappedDeclarationFiles(result.definitions); - if (mappedDefs === result.definitions) { - return result; - } - return { - definitions: mappedDefs, - textSpan: result.textSpan - }; + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position)); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } /// Goto implementation - var getTargetOfMappedImplementationLocation = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ - fileName: newLoc.fileName, - kind: info.kind, - displayParts: info.displayParts, - textSpan: { - start: newLoc.position, - length: info.textSpan.length - }, - originalFileName: info.fileName, - originalTextSpan: info.textSpan - }); }); - function getTargetOfMappedImplementationLocations(infos) { - return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); }); - } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedImplementationLocations(ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position)); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -109514,31 +113149,45 @@ var ts; }); }); }); } function getDocumentHighlights(fileName, position, filesToSearch) { - ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === fileName; })); + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function findRenameLocations(fileName, position, findInStrings, findInComments) { - return getReferences(fileName, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + } + else { + var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); + return refs && refs.map(function (_a) { + var fileName = _a.fileName, textSpan = _a.textSpan; + return ({ fileName: fileName, textSpan: textSpan }); + }); + } } function getReferencesAtPosition(fileName, position) { - return getReferences(fileName, position); + synchronizeHostData(); + return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); } - function getReferences(fileName, position, options) { + function getReferences(node, position, options) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, getValidSourceFile(fileName), position, options); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); } function findReferences(fileName, position) { synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } - /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); @@ -109556,10 +113205,11 @@ var ts; /** * This is a semantic operation. */ - function getSignatureHelpItems(fileName, position) { + function getSignatureHelpItems(fileName, position, _a) { + var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, cancellationToken); + return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); } /// Syntactic features function getNonBoundSourceFile(fileName) { @@ -109573,7 +113223,7 @@ var ts; return undefined; } switch (node.kind) { - case 185 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: case 146 /* QualifiedName */: case 9 /* StringLiteral */: case 86 /* FalseKeyword */: @@ -109581,7 +113231,7 @@ var ts; case 95 /* NullKeyword */: case 97 /* SuperKeyword */: case 99 /* ThisKeyword */: - case 174 /* ThisType */: + case 176 /* ThisType */: case 71 /* Identifier */: break; // Cant create the text span @@ -109598,7 +113248,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 239 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 242 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -109668,7 +113318,7 @@ var ts; braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var token = ts.getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); + var token = ts.getTouchingToken(sourceFile, position); var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined; var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile); // We want to order the braces when we return the result. @@ -109709,7 +113359,7 @@ var ts; return []; } function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { - if (preferences === void 0) { preferences = ts.defaultPreferences; } + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); @@ -109720,7 +113370,7 @@ var ts; }); } function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { - if (preferences === void 0) { preferences = ts.defaultPreferences; } + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); @@ -109728,7 +113378,7 @@ var ts; return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } function organizeImports(scope, formatOptions, preferences) { - if (preferences === void 0) { preferences = ts.defaultPreferences; } + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); @@ -109736,8 +113386,8 @@ var ts; return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { - if (preferences === void 0) { preferences = ts.defaultPreferences; } - return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences); + if (preferences === void 0) { preferences = ts.emptyOptions; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -109793,14 +113443,19 @@ var ts; return undefined; var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent : ts.isJsxText(token) ? token.parent : undefined; - if (element && !ts.tagNamesAreEquivalent(element.openingElement.tagName, element.closingElement.tagName)) { + if (element && isUnclosedTag(element)) { return { newText: "" }; } } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine); - return range && ts.createTextSpanFromRange(range); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); + return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined; } function getTodoComments(fileName, descriptors) { // Note: while getting todo comments seems like a syntactic operation, we actually @@ -109928,8 +113583,7 @@ var ts; } function getRenameInfo(fileName, position) { synchronizeHostData(); - var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); - return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); } function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -109945,13 +113599,13 @@ var ts; }; } function getApplicableRefactors(fileName, positionOrRange, preferences) { - if (preferences === void 0) { preferences = ts.defaultPreferences; } + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); var file = getValidSourceFile(fileName); return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); } function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { - if (preferences === void 0) { preferences = ts.defaultPreferences; } + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); var file = getValidSourceFile(fileName); return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); @@ -110008,7 +113662,8 @@ var ts; getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, - toLineColumnOffset: toLineColumnOffset + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, }; } ts.createLanguageService = createLanguageService; @@ -110024,7 +113679,7 @@ var ts; function initializeNameTable(sourceFile) { var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteral(node) && literalIsName(node)) { + if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { var text = ts.getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } @@ -110045,7 +113700,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 254 /* ExternalModuleReference */ || + node.parent.kind === 257 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -110054,6 +113709,11 @@ var ts; */ /* @internal */ function getContainingObjectLiteralElement(node) { + var element = getContainingObjectLiteralElementWorker(node); + return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined; + } + ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; + function getContainingObjectLiteralElementWorker(node) { switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -110063,46 +113723,49 @@ var ts; // falls through case 71 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 184 /* ObjectLiteralExpression */ || node.parent.parent.kind === 263 /* JsxAttributes */) && + (node.parent.parent.kind === 186 /* ObjectLiteralExpression */ || node.parent.parent.kind === 266 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; } - ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; - /* @internal */ - function getPropertySymbolsFromContextualType(typeChecker, node) { - var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); // TODO: GH#18217 - return getPropertySymbolsFromType(contextualType, node.name); // TODO: GH#18217 + function getSymbolAtLocationForQuickInfo(node, checker) { + var object = getContainingObjectLiteralElement(node); + if (object) { + var contextualType = checker.getContextualType(object.parent); + var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); + if (properties && properties.length === 1) { + return ts.first(properties); + } + } + return checker.getSymbolAtLocation(node); } - ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + /** Gets all symbols for one property. Does not get symbols for every property. */ /* @internal */ - function getPropertySymbolsFromType(type, propName) { - var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); - if (name && type) { - var result_2 = []; - var symbol = type.getProperty(name); - if (type.flags & 262144 /* Union */) { - ts.forEach(type.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_2.push(symbol); - } - }); - return result_2; - } - if (symbol) { - result_2.push(symbol); - return result_2; - } + function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + if (!contextualType.isUnion()) { + var symbol = contextualType.getProperty(name); + return symbol ? [symbol] : ts.emptyArray; } - return undefined; + var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); }); + if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { + var symbol = contextualType.getProperty(name); + if (symbol) + return [symbol]; + } + if (discriminatedPropertySymbols.length === 0) { + // Bad discriminant -- do again without discriminating + return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }); + } + return discriminatedPropertySymbols; } - ts.getPropertySymbolsFromType = getPropertySymbolsFromType; + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 186 /* ElementAccessExpression */ && + node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -110133,7 +113796,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line @@ -110182,114 +113845,114 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 214 /* VariableStatement */: + case 217 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: return spanInVariableDeclaration(node); case 149 /* Parameter */: return spanInParameterDeclaration(node); - case 234 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: case 155 /* Constructor */: - case 192 /* FunctionExpression */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 213 /* Block */: + case 216 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: return spanInBlock(node); - case 269 /* CatchClause */: + case 272 /* CatchClause */: return spanInBlock(node.block); - case 216 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 225 /* ReturnStatement */: + case 228 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 219 /* WhileStatement */: + case 222 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 218 /* DoStatement */: + case 221 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 231 /* DebuggerStatement */: + case 234 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 217 /* IfStatement */: + case 220 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 228 /* LabeledStatement */: + case 231 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 224 /* BreakStatement */: - case 223 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 220 /* ForStatement */: + case 223 /* ForStatement */: return spanInForStatement(node); - case 221 /* ForInStatement */: + case 224 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 222 /* ForOfStatement */: + case 225 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 227 /* SwitchStatement */: + case 230 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 266 /* CaseClause */: - case 267 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 230 /* TryStatement */: + case 233 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 229 /* ThrowStatement */: + case 232 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 249 /* ExportAssignment */: + case 252 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 243 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 244 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 250 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 235 /* ClassDeclaration */: - case 238 /* EnumDeclaration */: - case 273 /* EnumMember */: - case 182 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 184 /* BindingElement */: // span on complete node return textSpan(node); - case 226 /* WithStatement */: + case 229 /* WithStatement */: // span in statement return spanInNode(node.statement); case 150 /* Decorator */: return spanInNodeArray(parent.decorators); - case 180 /* ObjectBindingPattern */: - case 181 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 236 /* InterfaceDeclaration */: - case 237 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: return undefined; // Tokens: case 25 /* SemicolonToken */: @@ -110332,13 +113995,13 @@ var ts; // `a` or `...c` or `d: x` from // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 71 /* Identifier */ || - node.kind === 204 /* SpreadElement */ || - node.kind === 270 /* PropertyAssignment */ || - node.kind === 271 /* ShorthandPropertyAssignment */) && + node.kind === 206 /* SpreadElement */ || + node.kind === 273 /* PropertyAssignment */ || + node.kind === 274 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 200 /* BinaryExpression */) { + if (node.kind === 202 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -110360,22 +114023,22 @@ var ts; } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 218 /* DoStatement */: + case 221 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); case 150 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 220 /* ForStatement */: - case 222 /* ForOfStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: return textSpan(node); - case 200 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (node.parent.operatorToken.kind === 26 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 193 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -110384,20 +114047,20 @@ var ts; } } switch (node.parent.kind) { - case 270 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 190 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 232 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: case 149 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; @@ -110406,7 +114069,7 @@ var ts; } break; } - case 200 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -110436,7 +114099,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 221 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 224 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -110448,7 +114111,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - parent.parent.kind === 222 /* ForOfStatement */) { + parent.parent.kind === 225 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -110489,7 +114152,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 235 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */); + (functionDeclaration.parent.kind === 238 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -110512,26 +114175,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 239 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // falls through // Set on parent if on same line otherwise on first statement - case 219 /* WhileStatement */: - case 217 /* IfStatement */: - case 221 /* ForInStatement */: + case 222 /* WhileStatement */: + case 220 /* IfStatement */: + case 224 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 220 /* ForStatement */: - case 222 /* ForOfStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 233 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 236 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -110556,21 +114219,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 206 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 182 /* BindingElement */) { + if (bindingPattern.parent.kind === 184 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 181 /* ArrayBindingPattern */ && node.kind !== 180 /* ObjectBindingPattern */); - var elements = node.kind === 183 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 206 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 183 /* ArrayBindingPattern */ && node.kind !== 182 /* ObjectBindingPattern */); + var elements = node.kind === 185 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -110578,18 +114241,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 200 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 202 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 238 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 235 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -110597,25 +114260,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 240 /* ModuleBlock */: + case 243 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 238 /* EnumDeclaration */: - case 235 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 213 /* Block */: + case 216 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 269 /* CatchClause */: + case 272 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 241 /* CaseBlock */: + case 244 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -110623,7 +114286,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 180 /* ObjectBindingPattern */: + case 182 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -110639,7 +114302,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 181 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -110654,12 +114317,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 218 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 187 /* CallExpression */ || - node.parent.kind === 188 /* NewExpression */) { + if (node.parent.kind === 221 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 189 /* CallExpression */ || + node.parent.kind === 190 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 191 /* ParenthesizedExpression */) { + if (node.parent.kind === 193 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -110668,21 +114331,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 192 /* FunctionExpression */: - case 234 /* FunctionDeclaration */: - case 193 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: case 154 /* MethodDeclaration */: case 153 /* MethodSignature */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: case 155 /* Constructor */: - case 219 /* WhileStatement */: - case 218 /* DoStatement */: - case 220 /* ForStatement */: - case 222 /* ForOfStatement */: - case 187 /* CallExpression */: - case 188 /* NewExpression */: - case 191 /* ParenthesizedExpression */: + case 222 /* WhileStatement */: + case 221 /* DoStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 193 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -110692,20 +114355,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 270 /* PropertyAssignment */ || + node.parent.kind === 273 /* PropertyAssignment */ || node.parent.kind === 149 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 190 /* TypeAssertionExpression */) { + if (node.parent.kind === 192 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 218 /* DoStatement */) { + if (node.parent.kind === 221 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -110713,7 +114376,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 222 /* ForOfStatement */) { + if (node.parent.kind === 225 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -110866,7 +114529,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { var encoded = this.shimHost.getScriptFileNames(); - return this.files = JSON.parse(encoded); + return JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); @@ -111133,9 +114796,9 @@ var ts; return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; /// SIGNATUREHELP - LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { + LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); }); }; /// GOTO DEFINITION /** @@ -111521,435 +115184,6 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = ts.versionMajorMinor; -//# sourceMappingURL=services.js.map -"use strict"; -var ts; -(function (ts) { - var server; - (function (server) { - // tslint:disable variable-name - server.ActionSet = "action::set"; - server.ActionInvalidate = "action::invalidate"; - server.ActionPackageInstalled = "action::packageInstalled"; - server.EventTypesRegistry = "event::typesRegistry"; - server.EventBeginInstallTypes = "event::beginInstallTypes"; - server.EventEndInstallTypes = "event::endInstallTypes"; - server.EventInitializationFailed = "event::initializationFailed"; - var Arguments; - (function (Arguments) { - Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; - Arguments.LogFile = "--logFile"; - Arguments.EnableTelemetry = "--enableTelemetry"; - Arguments.TypingSafeListLocation = "--typingSafeListLocation"; - Arguments.TypesMapLocation = "--typesMapLocation"; - /** - * This argument specifies the location of the NPM executable. - * typingsInstaller will run the command with `${npmLocation} install ...`. - */ - Arguments.NpmLocation = "--npmLocation"; - })(Arguments = server.Arguments || (server.Arguments = {})); - function hasArgument(argumentName) { - return ts.sys.args.indexOf(argumentName) >= 0; - } - server.hasArgument = hasArgument; - function findArgument(argumentName) { - var index = ts.sys.args.indexOf(argumentName); - return index >= 0 && index < ts.sys.args.length - 1 - ? ts.sys.args[index + 1] - : undefined; - } - server.findArgument = findArgument; - /*@internal*/ - function nowString() { - // E.g. "12:34:56.789" - var d = new Date(); - return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); - } - server.nowString = nowString; - })(server = ts.server || (ts.server = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - /* @internal */ - function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); - } - JsTyping.isTypingUpToDate = isTypingUpToDate; - /* @internal */ - JsTyping.nodeCoreModuleList = [ - "assert", - "async_hooks", - "buffer", - "child_process", - "cluster", - "console", - "constants", - "crypto", - "dgram", - "dns", - "domain", - "events", - "fs", - "http", - "https", - "http2", - "inspector", - "net", - "os", - "path", - "perf_hooks", - "process", - "punycode", - "querystring", - "readline", - "repl", - "stream", - "string_decoder", - "timers", - "tls", - "tty", - "url", - "util", - "v8", - "vm", - "zlib" - ]; - /* @internal */ - JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList); - function loadSafeList(host, safeListPath) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - return ts.createMapFromTemplate(result.config); - } - JsTyping.loadSafeList = loadSafeList; - function loadTypesMap(host, typesMapPath) { - var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); }); - if (result.config) { - return ts.createMapFromTemplate(result.config.simpleMap); - } - return undefined; - } - JsTyping.loadTypesMap = loadTypesMap; - /** - * @param host is the object providing I/O related operations. - * @param fileNames are the file names that belong to the same project - * @param projectRootPath is the path to the project root directory - * @param safeListPath is the path used to retrieve the safe list - * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions - * @param typeAcquisition is used to customize the typing acquisition process - * @param compilerOptions are used as a source for typing inference - */ - function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { - if (!typeAcquisition || !typeAcquisition.enable) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - // A typing name to typing file path mapping - var inferredTypings = ts.createMap(); - // Only infer typings for .js and .jsx files - fileNames = ts.mapDefined(fileNames, function (fileName) { - var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { - return path; - } - }); - var filesToWatch = []; - if (typeAcquisition.include) - addInferredTypings(typeAcquisition.include, "Explicitly included types"); - var exclude = typeAcquisition.exclude || []; - // Directories to search for package.json, bower.json and other typing information - var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); - possibleSearchDirs.set(projectRootPath, true); - possibleSearchDirs.forEach(function (_true, searchDir) { - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); - }); - getTypingNamesFromSourceFileNames(fileNames); - // add typings for unresolved imports - if (unresolvedImports) { - var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); - addInferredTypings(module_1, "Inferred typings from unresolved imports"); - } - // Add the cached typing locations for inferred typings that are already installed - packageNameToTypingLocation.forEach(function (typing, name) { - var registryEntry = typesRegistry.get(name); - if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { - inferredTypings.set(name, typing.typingLocation); - } - }); - // Remove typings that the user has added to the exclude list - for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { - var excludeTypingName = exclude_1[_i]; - var didDelete = inferredTypings.delete(excludeTypingName); - if (didDelete && log) - log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); - } - var newTypingNames = []; - var cachedTypingPaths = []; - inferredTypings.forEach(function (inferred, typing) { - if (inferred !== undefined) { - cachedTypingPaths.push(inferred); - } - else { - newTypingNames.push(typing); - } - }); - var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - if (log) - log("Result: " + JSON.stringify(result)); - return result; - function addInferredTyping(typingName) { - if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); // TODO: GH#18217 - } - } - function addInferredTypings(typingNames, message) { - if (log) - log(message + ": " + JSON.stringify(typingNames)); - ts.forEach(typingNames, addInferredTyping); - } - /** - * Get the typing info from common package manager json files like package.json or bower.json - */ - function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (!host.fileExists(jsonPath)) { - return; - } - filesToWatch.push(jsonPath); - var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; - var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); - addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); - } - /** - * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" - * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred - * to the 'angular-route' typing name. - * @param fileNames are the names for source files in the project - */ - function getTypingNamesFromSourceFileNames(fileNames) { - var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) - return undefined; - var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); - var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - return safeList.get(cleanedTypingName); - }); - if (fromFileNames.length) { - addInferredTypings(fromFileNames, "Inferred typings from file names"); - } - var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); - if (hasJsxFile) { - if (log) - log("Inferred 'react' typings due to presence of '.jsx' extension"); - addInferredTyping("react"); - } - } - /** - * Infer typing names from packages folder (ex: node_module, bower_components) - * @param packagesFolderPath is the path to the packages folder - */ - function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { - filesToWatch.push(packagesFolderPath); - // Todo: add support for ModuleResolutionHost too - if (!host.directoryExists(packagesFolderPath)) { - return; - } - // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` - var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); - if (log) - log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); - var packageNames = []; - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; - var normalizedFileName = ts.normalizePath(fileName); - var baseFileName = ts.getBaseFileName(normalizedFileName); - if (baseFileName !== "package.json" && baseFileName !== "bower.json") { - continue; - } - var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_1.config; - // npm 3's package.json contains a "_requiredBy" field - // we should include all the top level module names for npm 2, and only module names whose - // "_requiredBy" field starts with "#" or equals "/" for npm 3. - if (baseFileName === "package.json" && packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used - // to download d.ts files from DefinitelyTyped - if (!packageJson.name) { - continue; - } - var ownTypes = packageJson.types || packageJson.typings; - if (ownTypes) { - var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); - if (log) - log(" Package '" + packageJson.name + "' provides its own types."); - inferredTypings.set(packageJson.name, absolutePath); - } - else { - packageNames.push(packageJson.name); - } - } - addInferredTypings(packageNames, " Found package names"); - } - } - JsTyping.discoverTypings = discoverTypings; - var PackageNameValidationResult; - (function (PackageNameValidationResult) { - PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; - PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; - PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; - PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; - PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; - })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); - var maxPackageNameLength = 214; - /** - * Validates package name using rules defined at https://docs.npmjs.com/files/package.json - */ - function validatePackageName(packageName) { - if (!packageName) { - return 2 /* EmptyName */; - } - if (packageName.length > maxPackageNameLength) { - return 3 /* NameTooLong */; - } - if (packageName.charCodeAt(0) === 46 /* dot */) { - return 4 /* NameStartsWithDot */; - } - if (packageName.charCodeAt(0) === 95 /* _ */) { - return 5 /* NameStartsWithUnderscore */; - } - // check if name is scope package like: starts with @ and has one '/' in the middle - // scoped packages are not currently supported - // TODO: when support will be added we'll need to split and check both scope and package name - if (/^@[^/]+\/[^/]+$/.test(packageName)) { - return 1 /* ScopedPackagesNotSupported */; - } - if (encodeURIComponent(packageName) !== packageName) { - return 6 /* NameContainsNonURISafeCharacters */; - } - return 0 /* Ok */; - } - JsTyping.validatePackageName = validatePackageName; - function renderPackageNameValidationFailure(result, typing) { - switch (result) { - case 2 /* EmptyName */: - return "Package name '" + typing + "' cannot be empty"; - case 3 /* NameTooLong */: - return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; - case 4 /* NameStartsWithDot */: - return "Package name '" + typing + "' cannot start with '.'"; - case 5 /* NameStartsWithUnderscore */: - return "Package name '" + typing + "' cannot start with '_'"; - case 1 /* ScopedPackagesNotSupported */: - return "Package '" + typing + "' is scoped and currently is not supported"; - case 6 /* NameContainsNonURISafeCharacters */: - return "Package name '" + typing + "' contains non URI safe characters"; - case 0 /* Ok */: - return ts.Debug.fail(); // Shouldn't have called this. - default: - throw ts.Debug.assertNever(result); - } - } - JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); -//# sourceMappingURL=jsTyping.js.map -"use strict"; -var __assign = (this && this.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; -}; -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); var ts; (function (ts) { var server; @@ -111962,6 +115196,7 @@ var ts; LogLevel[LogLevel["verbose"] = 3] = "verbose"; })(LogLevel = server.LogLevel || (server.LogLevel = {})); server.emptyArray = createSortedArray(); + // TODO: Use a const enum (https://github.com/Microsoft/TypeScript/issues/16804) var Msg; (function (Msg) { Msg["Err"] = "Err"; @@ -111971,7 +115206,7 @@ var ts; function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), - fileNames: project.getFileNames(true, true).concat(project.getExcludedFiles()), + fileNames: project.getFileNames(/*excludeFilesFromExternalLibraries*/ true, /*excludeConfigFiles*/ true).concat(project.getExcludedFiles()), compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, @@ -112052,6 +115287,7 @@ var ts; } server.createNormalizedPathMap = createNormalizedPathMap; function isInferredProjectName(name) { + // POSIX defines /dev/null as a device - there should be no file with this prefix return /dev\/null\/inferredProject\d+\*/.test(name); } server.isInferredProjectName = isInferredProjectName; @@ -112060,25 +115296,34 @@ var ts; } server.makeInferredProjectName = makeInferredProjectName; function createSortedArray() { - return []; + return []; // TODO: GH#19873 } server.createSortedArray = createSortedArray; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/* @internal */ (function (ts) { var server; (function (server) { - var ThrottledOperations = (function () { + var ThrottledOperations = /** @class */ (function () { function ThrottledOperations(host, logger) { this.host = host; this.pendingTimeouts = ts.createMap(); this.logger = logger.hasLevel(server.LogLevel.verbose) ? logger : undefined; } + /** + * Wait `number` milliseconds and then invoke `cb`. If, while waiting, schedule + * is called again with the same `operationId`, cancel this operation in favor + * of the new one. (Note that the amount of time the canceled operation had been + * waiting does not affect the amount of time that the new operation waits.) + */ ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { var pendingTimeout = this.pendingTimeouts.get(operationId); if (pendingTimeout) { + // another operation was already scheduled for this id - cancel it this.host.clearTimeout(pendingTimeout); } + // schedule new operation, pass arguments this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb)); if (this.logger) { this.logger.info("Scheduled: " + operationId + (pendingTimeout ? ", Cancelled earlier one" : "")); @@ -112094,7 +115339,7 @@ var ts; return ThrottledOperations; }()); server.ThrottledOperations = ThrottledOperations; - var GcTimer = (function () { + var GcTimer = /** @class */ (function () { function GcTimer(host, delay, logger) { this.host = host; this.delay = delay; @@ -112102,6 +115347,7 @@ var ts; } GcTimer.prototype.scheduleCollect = function () { if (!this.host.gc || this.timerId !== undefined) { + // no global.gc or collection was already scheduled - skip this request return; } this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); @@ -112109,10 +115355,10 @@ var ts; GcTimer.run = function (self) { self.timerId = undefined; var log = self.logger.hasLevel(server.LogLevel.requestTime); - var before = log && self.host.getMemoryUsage(); - self.host.gc(); + var before = log && self.host.getMemoryUsage(); // TODO: GH#18217 + self.host.gc(); // TODO: GH#18217 if (log) { - var after = self.host.getMemoryUsage(); + var after = self.host.getMemoryUsage(); // TODO: GH#18217 self.logger.perftrc("GC::before " + before + ", after " + after); } }; @@ -112152,49 +115398,70 @@ var ts; function isNonDuplicateInSortedArray(value, index, array) { return index === 0 || value !== array[index - 1]; } + /* @internal */ function indent(str) { return "\n " + str; } server.indent = indent; + /** Put stringified JSON on the next line, indented. */ + /* @internal */ function stringifyIndented(json) { return "\n " + JSON.stringify(json); } server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +// tslint:disable no-unnecessary-qualifier +/** + * Declaration module describing the TypeScript Server protocol + */ var ts; (function (ts) { var server; (function (server) { var protocol; (function (protocol) { + // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. var CommandTypes; (function (CommandTypes) { CommandTypes["JsxClosingTag"] = "jsxClosingTag"; CommandTypes["Brace"] = "brace"; + /* @internal */ CommandTypes["BraceFull"] = "brace-full"; CommandTypes["BraceCompletion"] = "braceCompletion"; CommandTypes["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment"; CommandTypes["Change"] = "change"; CommandTypes["Close"] = "close"; + /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */ CommandTypes["Completions"] = "completions"; + CommandTypes["CompletionInfo"] = "completionInfo"; + /* @internal */ CommandTypes["CompletionsFull"] = "completions-full"; CommandTypes["CompletionDetails"] = "completionEntryDetails"; + /* @internal */ CommandTypes["CompletionDetailsFull"] = "completionEntryDetails-full"; CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList"; CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile"; CommandTypes["Configure"] = "configure"; CommandTypes["Definition"] = "definition"; + /* @internal */ CommandTypes["DefinitionFull"] = "definition-full"; CommandTypes["DefinitionAndBoundSpan"] = "definitionAndBoundSpan"; + /* @internal */ CommandTypes["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full"; CommandTypes["Implementation"] = "implementation"; + /* @internal */ CommandTypes["ImplementationFull"] = "implementation-full"; + /* @internal */ + CommandTypes["EmitOutput"] = "emit-output"; CommandTypes["Exit"] = "exit"; CommandTypes["Format"] = "format"; CommandTypes["Formatonkey"] = "formatonkey"; + /* @internal */ CommandTypes["FormatFull"] = "format-full"; + /* @internal */ CommandTypes["FormatonkeyFull"] = "formatonkey-full"; + /* @internal */ CommandTypes["FormatRangeFull"] = "formatRange-full"; CommandTypes["Geterr"] = "geterr"; CommandTypes["GeterrForProject"] = "geterrForProject"; @@ -112202,25 +115469,34 @@ var ts; CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync"; CommandTypes["NavBar"] = "navbar"; + /* @internal */ CommandTypes["NavBarFull"] = "navbar-full"; CommandTypes["Navto"] = "navto"; + /* @internal */ CommandTypes["NavtoFull"] = "navto-full"; CommandTypes["NavTree"] = "navtree"; CommandTypes["NavTreeFull"] = "navtree-full"; + /** @deprecated */ CommandTypes["Occurrences"] = "occurrences"; CommandTypes["DocumentHighlights"] = "documentHighlights"; + /* @internal */ CommandTypes["DocumentHighlightsFull"] = "documentHighlights-full"; CommandTypes["Open"] = "open"; CommandTypes["Quickinfo"] = "quickinfo"; + /* @internal */ CommandTypes["QuickinfoFull"] = "quickinfo-full"; CommandTypes["References"] = "references"; + /* @internal */ CommandTypes["ReferencesFull"] = "references-full"; CommandTypes["Reload"] = "reload"; CommandTypes["Rename"] = "rename"; + /* @internal */ CommandTypes["RenameInfoFull"] = "rename-full"; + /* @internal */ CommandTypes["RenameLocationsFull"] = "renameLocations-full"; CommandTypes["Saveto"] = "saveto"; CommandTypes["SignatureHelp"] = "signatureHelp"; + /* @internal */ CommandTypes["SignatureHelpFull"] = "signatureHelp-full"; CommandTypes["Status"] = "status"; CommandTypes["TypeDefinition"] = "typeDefinition"; @@ -112230,32 +115506,46 @@ var ts; CommandTypes["OpenExternalProject"] = "openExternalProject"; CommandTypes["OpenExternalProjects"] = "openExternalProjects"; CommandTypes["CloseExternalProject"] = "closeExternalProject"; + /* @internal */ CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList"; + /* @internal */ CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles"; + /* @internal */ CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; + /* @internal */ CommandTypes["Cleanup"] = "cleanup"; CommandTypes["GetOutliningSpans"] = "getOutliningSpans"; + /* @internal */ CommandTypes["GetOutliningSpansFull"] = "outliningSpans"; CommandTypes["TodoComments"] = "todoComments"; CommandTypes["Indentation"] = "indentation"; CommandTypes["DocCommentTemplate"] = "docCommentTemplate"; + /* @internal */ CommandTypes["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full"; + /* @internal */ CommandTypes["NameOrDottedNameSpan"] = "nameOrDottedNameSpan"; + /* @internal */ CommandTypes["BreakpointStatement"] = "breakpointStatement"; CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; CommandTypes["GetCodeFixes"] = "getCodeFixes"; + /* @internal */ CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; CommandTypes["GetCombinedCodeFix"] = "getCombinedCodeFix"; + /* @internal */ CommandTypes["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full"; CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor"; + /* @internal */ CommandTypes["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; CommandTypes["OrganizeImports"] = "organizeImports"; + /* @internal */ CommandTypes["OrganizeImportsFull"] = "organizeImports-full"; CommandTypes["GetEditsForFileRename"] = "getEditsForFileRename"; + /* @internal */ CommandTypes["GetEditsForFileRenameFull"] = "getEditsForFileRename-full"; + // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); var IndentStyle; (function (IndentStyle) { @@ -112308,17 +115598,18 @@ var ts; (function (ts) { var server; (function (server) { - var TextStorage = (function () { - function TextStorage(host, fileName) { + /* @internal */ + var TextStorage = /** @class */ (function () { + function TextStorage(host, fileName, initialVersion, info) { this.host = host; this.fileName = fileName; - this.svcVersion = 0; - this.textVersion = 0; + this.info = info; + this.version = initialVersion || { svc: 0, text: 0 }; } TextStorage.prototype.getVersion = function () { return this.svc - ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshotVersion() - : "Text-" + this.textVersion; + ? "SVC-" + this.version.svc + "-" + this.svc.getSnapshotVersion() + : "Text-" + this.version.text; }; TextStorage.prototype.hasScriptVersionCache_TestOnly = function () { return this.svc !== undefined; @@ -112330,7 +115621,7 @@ var ts; this.svc = undefined; this.text = newText; this.lineMap = undefined; - this.textVersion++; + this.version.text++; }; TextStorage.prototype.edit = function (start, end, newText) { this.switchToScriptVersionCache().edit(start, end - start, newText); @@ -112338,20 +115629,39 @@ var ts; this.text = undefined; this.lineMap = undefined; }; + /** + * Set the contents as newText + * returns true if text changed + */ TextStorage.prototype.reload = function (newText) { ts.Debug.assert(newText !== undefined); + // Reload always has fresh content this.pendingReloadFromDisk = false; + // If text changed set the text + // This also ensures that if we had switched to version cache, + // we are switching back to text. + // The change to version cache will happen when needed + // Thus avoiding the computation if there are no changes if (this.text !== newText) { this.useText(newText); + // We cant guarantee new text is own file text this.ownFileText = false; return true; } }; + /** + * Reads the contents from tempFile(if supplied) or own file and sets it as contents + * returns true if text changed + */ TextStorage.prototype.reloadWithFileText = function (tempFileName) { var reloaded = this.reload(this.getFileText(tempFileName)); this.ownFileText = !tempFileName || tempFileName === this.fileName; return reloaded; }; + /** + * Reloads the contents from the file if there is no pending reload from disk or the contents of file are same as file text + * returns true if text changed + */ TextStorage.prototype.reloadFromDisk = function () { if (!this.pendingReloadFromDisk && !this.ownFileText) { return this.reloadWithFileText(); @@ -112369,19 +115679,27 @@ var ts; TextStorage.prototype.getLineInfo = function (line) { return this.switchToScriptVersionCache().getLineInfo(line); }; + /** + * @param line 0 based index + */ TextStorage.prototype.lineToTextSpan = function (line) { if (!this.useScriptVersionCacheIfValidOrOpen()) { var lineMap = this.getLineMap(); - var start = lineMap[line]; + var start = lineMap[line]; // -1 since line is 1-based var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; return ts.createTextSpanFromBounds(start, end); } return this.svc.lineToTextSpan(line); }; + /** + * @param line 1 based index + * @param offset 1 based index + */ TextStorage.prototype.lineOffsetToPosition = function (line, offset) { if (!this.useScriptVersionCacheIfValidOrOpen()) { return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); } + // TODO: assert this offset is actually on the line return this.svc.lineOffsetToPosition(line, offset); }; TextStorage.prototype.positionToLineOffset = function (position) { @@ -112392,22 +115710,40 @@ var ts; return this.svc.positionToLineOffset(position); }; TextStorage.prototype.getFileText = function (tempFileName) { - return this.host.readFile(tempFileName || this.fileName) || ""; + var _this = this; + var text; + var fileName = tempFileName || this.fileName; + var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; + // Only non typescript files have size limitation + if (!ts.hasTypeScriptFileExtension(this.fileName)) { + var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; + if (fileSize > server.maxFileSize) { + ts.Debug.assert(!!this.info.containingProjects.length); + var service = this.info.containingProjects[0].projectService; + service.logger.info("Skipped loading contents of large file " + fileName + " for info " + this.info.fileName + ": fileSize: " + fileSize); + this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); + return ""; + } + } + return getText(); }; TextStorage.prototype.switchToScriptVersionCache = function () { if (!this.svc || this.pendingReloadFromDisk) { this.svc = server.ScriptVersionCache.fromString(this.getOrLoadText()); - this.svcVersion++; + this.version.svc++; } return this.svc; }; TextStorage.prototype.useScriptVersionCacheIfValidOrOpen = function () { + // If this is open script, use the cache if (this.isOpen) { return this.switchToScriptVersionCache(); } + // If there is pending reload from the disk then, reload the text if (this.pendingReloadFromDisk) { this.reloadWithFileText(); } + // At this point if svc is present its valid return this.svc; }; TextStorage.prototype.getOrLoadText = function () { @@ -112424,20 +115760,24 @@ var ts; return TextStorage; }()); server.TextStorage = TextStorage; + /*@internal*/ function isDynamicFileName(fileName) { return fileName[0] === "^" || ts.getBaseFileName(fileName)[0] === "^"; } server.isDynamicFileName = isDynamicFileName; - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path) { + var ScriptInfo = /** @class */ (function () { + function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path, initialVersion) { this.host = host; this.fileName = fileName; this.scriptKind = scriptKind; this.hasMixedContent = hasMixedContent; this.path = path; + /** + * All projects that include this file + */ this.containingProjects = []; this.isDynamic = isDynamicFileName(fileName); - this.textStorage = new TextStorage(host, fileName); + this.textStorage = new TextStorage(host, fileName, initialVersion, this); if (hasMixedContent || this.isDynamic) { this.textStorage.reload(""); this.realpath = this.path; @@ -112446,6 +115786,11 @@ var ts; ? scriptKind : ts.getScriptKindFromFileName(fileName); } + /*@internal*/ + ScriptInfo.prototype.getVersion = function () { + return this.textStorage.version; + }; + /*@internal*/ ScriptInfo.prototype.isDynamicOrHasMixedContent = function () { return this.hasMixedContent || this.isDynamic; }; @@ -112456,6 +115801,7 @@ var ts; this.textStorage.isOpen = true; if (newText !== undefined && this.textStorage.reload(newText)) { + // reload new contents only if the existing contents changed this.markContainingProjectsAsDirty(); } }; @@ -112476,6 +115822,7 @@ var ts; }; ScriptInfo.prototype.ensureRealPath = function () { if (this.realpath === undefined) { + // Default is just the path this.realpath = this.path; if (this.host.realpath) { ts.Debug.assert(!!this.containingProjects.length); @@ -112483,13 +115830,15 @@ var ts; var realpath = this.host.realpath(this.path); if (realpath) { this.realpath = project.toPath(realpath); + // If it is different from this.path, add to the map if (this.realpath !== this.path) { - project.projectService.realpathToScriptInfos.add(this.realpath, this); + project.projectService.realpathToScriptInfos.add(this.realpath, this); // TODO: GH#18217 } } } } }; + /*@internal*/ ScriptInfo.prototype.getRealpathIfDifferent = function () { return this.realpath && this.realpath !== this.path ? this.realpath : undefined; }; @@ -112507,6 +115856,7 @@ var ts; return isNew; }; ScriptInfo.prototype.isAttached = function (project) { + // unrolled for common cases switch (this.containingProjects.length) { case 0: return false; case 1: return this.containingProjects[0] === project; @@ -112515,6 +115865,7 @@ var ts; } }; ScriptInfo.prototype.detachFromProject = function (project) { + // unrolled for common cases switch (this.containingProjects.length) { case 0: return; @@ -112548,7 +115899,10 @@ var ts; p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); } var isInfoRoot = p.isRoot(this); - p.removeFile(this, false, false); + // detach is unnecessary since we'll clean the list of containing projects anyways + p.removeFile(this, /*fileExists*/ false, /*detachFromProjects*/ false); + // If the info was for the external or configured project's root, + // add missing file as the root if (isInfoRoot && p.projectKind !== server.ProjectKind.Inferred) { p.addMissingFileRoot(this.fileName); } @@ -112562,6 +115916,9 @@ var ts; case 1: return this.containingProjects[0]; default: + // if this file belongs to multiple projects, the first configured project should be + // the default project; if no configured projects, the first external project should + // be the default project; otherwise the first inferred project should be the default. var firstExternalProject = void 0; for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; @@ -112593,7 +115950,7 @@ var ts; } if (preferences) { if (!this.preferences) { - this.preferences = ts.defaultPreferences; + this.preferences = ts.emptyOptions; } this.preferences = __assign({}, this.preferences, preferences); } @@ -112604,6 +115961,7 @@ var ts; ScriptInfo.prototype.saveTo = function (fileName) { this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot())); }; + /*@internal*/ ScriptInfo.prototype.delayReloadNonMixedContentFile = function () { ts.Debug.assert(!this.isDynamicOrHasMixedContent()); this.textStorage.delayReloadFromFileIntoText(); @@ -112613,13 +115971,17 @@ var ts; if (this.isDynamicOrHasMixedContent()) { this.textStorage.reload(""); this.markContainingProjectsAsDirty(); + return true; } else { if (this.textStorage.reloadWithFileText(tempFileName)) { this.markContainingProjectsAsDirty(); + return true; } } + return false; }; + /*@internal*/ ScriptInfo.prototype.getLineInfo = function (line) { return this.textStorage.getLineInfo(line); }; @@ -112636,9 +115998,16 @@ var ts; ScriptInfo.prototype.isOrphan = function () { return !ts.forEach(this.containingProjects, function (p) { return !p.isOrphan(); }); }; + /** + * @param line 1 based index + */ ScriptInfo.prototype.lineToTextSpan = function (line) { return this.textStorage.lineToTextSpan(line); }; + /** + * @param line 1 based index + * @param offset 1 based index + */ ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { return this.textStorage.lineOffsetToPosition(line, offset); }; @@ -112646,7 +116015,7 @@ var ts; return this.textStorage.positionToLineOffset(position); }; ScriptInfo.prototype.isJavaScript = function () { - return this.scriptKind === 1 || this.scriptKind === 2; + return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */; }; return ScriptInfo; }()); @@ -112659,11 +116028,12 @@ var ts; (function (server) { server.nullTypingsInstaller = { isKnownTypesPackageName: ts.returnFalse, + // Should never be called because we never provide a types registry. installPackage: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, - globalTypingsCacheLocation: undefined + globalTypingsCacheLocation: undefined // TODO: GH#18217 }; function setIsEqualTo(arr1, arr2) { if (arr1 === arr2) { @@ -112700,6 +116070,7 @@ var ts; !setIsEqualTo(opt1.exclude, opt2.exclude); } function compilerOptionsChanged(opt1, opt2) { + // TODO: add more relevant properties return opt1.allowJs !== opt2.allowJs; } function unresolvedImportsChanged(imports1, imports2) { @@ -112708,7 +116079,8 @@ var ts; } return !ts.arrayIsEqualTo(imports1, imports2); } - var TypingsCache = (function () { + /*@internal*/ + var TypingsCache = /** @class */ (function () { function TypingsCache(installer) { this.installer = installer; this.perProjectCache = ts.createMap(); @@ -112730,6 +116102,8 @@ var ts; typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) || unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { + // Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options. + // instead it acts as a placeholder to prevent issuing multiple requests this.perProjectCache.set(project.getProjectName(), { compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, @@ -112737,6 +116111,7 @@ var ts; unresolvedImports: unresolvedImports, poisoned: true }); + // something has been changed, issue a request to update typings this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } }; @@ -112770,26 +116145,27 @@ var ts; ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; ProjectKind[ProjectKind["External"] = 2] = "External"; })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); + /* @internal */ function countEachFileTypes(infos) { var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0, deferred: 0 }; - for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { - var info = infos_1[_i]; + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; switch (info.scriptKind) { - case 1: + case 1 /* JS */: result.js += 1; break; - case 2: + case 2 /* JSX */: result.jsx += 1; break; - case 3: - ts.fileExtensionIs(info.fileName, ".d.ts") + case 3 /* TS */: + ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */) ? result.dts += 1 : result.ts += 1; break; - case 4: + case 4 /* TSX */: result.tsx += 1; break; - case 7: + case 7 /* Deferred */: result.deferred += 1; break; } @@ -112811,16 +116187,20 @@ var ts; return counts.ts === 0 && counts.tsx === 0; } server.allFilesAreJsOrDts = allFilesAreJsOrDts; + /* @internal */ function hasNoTypeScriptSource(fileNames) { - return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts") && !ts.fileExtensionIs(fileName, ".d.ts")) || ts.fileExtensionIs(fileName, ".tsx"); }); + return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts" /* Ts */) && !ts.fileExtensionIs(fileName, ".d.ts" /* Dts */)) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */); }); } server.hasNoTypeScriptSource = hasNoTypeScriptSource; + /* @internal */ function isScriptInfo(value) { return value instanceof server.ScriptInfo; } server.isScriptInfo = isScriptInfo; - var Project = (function () { - function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { + var Project = /** @class */ (function () { + /*@internal*/ + function Project( + /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { var _this = this; this.projectName = projectName; this.projectKind = projectKind; @@ -112831,13 +116211,36 @@ var ts; this.rootFiles = []; this.rootFilesMap = ts.createMap(); this.plugins = []; + /*@internal*/ + /** + * This is map from files to unresolved imports in it + * Maop does not contain entries for files that do not have unresolved imports + * This helps in containing the set of files to invalidate + */ this.cachedUnresolvedImportsPerFile = ts.createMap(); + /*@internal*/ this.hasAddedorRemovedFiles = false; + /** + * Last version that was reported. + */ this.lastReportedVersion = 0; + /** + * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one) + * This property is changed in 'updateGraph' based on the set of files in program + */ this.projectProgramVersion = 0; + /** + * Current version of the project state. It is changed when: + * - new root file was added/removed + * - edit happen in some file that is currently included in the project. + * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project + */ this.projectStateVersion = 0; + /*@internal*/ this.dirty = false; + /*@internal*/ this.hasChangedAutomaticTypeDirectiveNames = false; + /*@internal*/ this.typingFiles = server.emptyArray; this.directoryStructureHost = directoryStructureHost; this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); @@ -112849,6 +116252,7 @@ var ts; this.compilerOptions.allowJs = true; } else if (hasExplicitListOfFiles || this.compilerOptions.allowJs || this.projectService.hasDeferredExtension()) { + // If files are listed explicitly or allowJs is specified, allow all extensions this.compilerOptions.allowNonTsExtensions = true; } this.languageServiceEnabled = !projectService.syntaxOnly; @@ -112863,7 +116267,8 @@ var ts; if (host.realpath) { this.realpath = function (path) { return host.realpath(path); }; } - this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, true); + // Use the current directory as resolution root only if the project created using current directory string + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true); this.languageService = ts.createLanguageService(this, this.documentRegistry, projectService.syntaxOnly); if (lastFileExceededProgramSize) { this.disableLanguageService(lastFileExceededProgramSize); @@ -112872,17 +116277,17 @@ var ts; this.projectService.pendingEnsureProjectForOpenFiles = true; } Project.prototype.isNonTsProject = function () { - this.updateGraph(); + server.updateProjectIfDirty(this); return allFilesAreJsOrDts(this); }; Project.prototype.isJsOnlyProject = function () { - this.updateGraph(); + server.updateProjectIfDirty(this); return hasOneOrMoreJsAndNoTsFiles(this); }; Project.resolveModule = function (moduleName, initialDir, host, log) { var resolvedPath = ts.normalizeSlashes(host.resolvePath(ts.combinePaths(initialDir, "node_modules"))); log("Loading " + moduleName + " from " + initialDir + " (resolved to " + resolvedPath + ")"); - var result = host.require(resolvedPath, moduleName); + var result = host.require(resolvedPath, moduleName); // TODO: GH#18217 if (result.error) { var err = result.error.stack || result.error.message || JSON.stringify(result.error); log("Failed to load module '" + moduleName + "': " + err); @@ -112903,9 +116308,11 @@ var ts; enumerable: true, configurable: true }); + // Method of LanguageServiceHost Project.prototype.getCompilationSettings = function () { return this.compilerOptions; }; + // Method to support public API Project.prototype.getCompilerOptions = function () { return this.getCompilationSettings(); }; @@ -112916,7 +116323,7 @@ var ts; return this.projectStateVersion.toString(); }; Project.prototype.getProjectReferences = function () { - return undefined; + return server.emptyArray; }; Project.prototype.getScriptFileNames = function () { var _this = this; @@ -112926,6 +116333,7 @@ var ts; var result; this.rootFilesMap.forEach(function (value) { if (_this.languageServiceEnabled || (isScriptInfo(value) && value.isScriptOpen())) { + // if language service is disabled - process only files that are open (result || (result = [])).push(isScriptInfo(value) ? value.fileName : value); } }); @@ -112936,6 +116344,7 @@ var ts; if (scriptInfo) { var existingValue = this.rootFilesMap.get(scriptInfo.path); if (existingValue !== scriptInfo && existingValue !== undefined) { + // This was missing path earlier but now the file exists. Update the root this.rootFiles.push(scriptInfo); this.rootFilesMap.set(scriptInfo.path, scriptInfo); } @@ -112945,11 +116354,11 @@ var ts; }; Project.prototype.getScriptKind = function (fileName) { var info = this.getOrCreateScriptInfoAndAttachToProject(fileName); - return (info && info.scriptKind); + return (info && info.scriptKind); // TODO: GH#18217 }; Project.prototype.getScriptVersion = function (filename) { var info = this.getOrCreateScriptInfoAndAttachToProject(filename); - return (info && info.getLatestVersion()); + return (info && info.getLatestVersion()); // TODO: GH#18217 }; Project.prototype.getScriptSnapshot = function (filename) { var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename); @@ -112977,6 +116386,8 @@ var ts; return this.projectService.host.readFile(fileName); }; Project.prototype.fileExists = function (file) { + // As an optimization, don't hit the disks for files we already know don't exist + // (because we're watching for their creation). var path = this.toPath(file); return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); }; @@ -112990,33 +116401,41 @@ var ts; return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; Project.prototype.directoryExists = function (path) { - return this.directoryStructureHost.directoryExists(path); + return this.directoryStructureHost.directoryExists(path); // TODO: GH#18217 }; Project.prototype.getDirectories = function (path) { - return this.directoryStructureHost.getDirectories(path); + return this.directoryStructureHost.getDirectories(path); // TODO: GH#18217 }; + /*@internal*/ Project.prototype.getCachedDirectoryStructureHost = function () { - return undefined; + return undefined; // TODO: GH#18217 }; + /*@internal*/ Project.prototype.toPath = function (fileName) { return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); }; + /*@internal*/ Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution", this); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution" /* FailedLookupLocation */, this); }; + /*@internal*/ Project.prototype.onInvalidatedResolution = function () { this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); }; + /*@internal*/ Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory", this); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory" /* TypeRoots */, this); }; + /*@internal*/ Project.prototype.onChangedAutomaticTypeDirectiveNames = function () { this.hasChangedAutomaticTypeDirectiveNames = true; this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); }; + /*@internal*/ Project.prototype.getGlobalCache = function () { return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined; }; + /*@internal*/ Project.prototype.writeLog = function (s) { this.projectService.logger.info(s); }; @@ -113031,6 +116450,9 @@ var ts; this.compilerOptions.noEmitForJsFiles = true; } }; + /** + * Get the errors that dont have any file name associated + */ Project.prototype.getGlobalProjectErrors = function () { return server.emptyArray; }; @@ -113040,10 +116462,14 @@ var ts; Project.prototype.getLanguageService = function (ensureSynchronized) { if (ensureSynchronized === void 0) { ensureSynchronized = true; } if (ensureSynchronized) { - this.updateGraph(); + server.updateProjectIfDirty(this); } return this.languageService; }; + /** @internal */ + Project.prototype.getSourceMapper = function () { + return this.getLanguageService().getSourceMapper(); + }; Project.prototype.shouldEmitFile = function (scriptInfo) { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); }; @@ -113052,15 +116478,20 @@ var ts; if (!this.languageServiceEnabled) { return []; } - this.updateGraph(); + server.updateProjectIfDirty(this); this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); - return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), // TODO: GH#18217 + function (// TODO: GH#18217 + sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; + /** + * Returns true if emit was conducted + */ Project.prototype.emitFile = function (scriptInfo, writeFile) { if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { return false; } - var _a = this.getLanguageService(false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + var _a = this.getLanguageService(/*ensureSynchronized*/ false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; if (!emitSkipped) { for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { var outputFile = outputFiles_1[_i]; @@ -113076,7 +116507,7 @@ var ts; } this.languageServiceEnabled = true; this.lastFileExceededProgramSize = undefined; - this.projectService.onUpdateLanguageServiceStateForProject(this, true); + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ true); }; Project.prototype.disableLanguageService = function (lastFileExceededProgramSize) { if (!this.languageServiceEnabled) { @@ -113088,13 +116519,14 @@ var ts; this.lastFileExceededProgramSize = lastFileExceededProgramSize; this.builderState = undefined; this.resolutionCache.closeTypeRootsWatch(); - this.projectService.onUpdateLanguageServiceStateForProject(this, false); + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false); }; Project.prototype.getProjectName = function () { return this.projectName; }; Project.prototype.removeLocalTypingsFromTypeAcquisition = function (newTypeAcquisition) { if (!newTypeAcquisition || !newTypeAcquisition.include) { + // Nothing to filter out, so just return as-is return newTypeAcquisition; } return __assign({}, newTypeAcquisition, { include: this.removeExistingTypings(newTypeAcquisition.include) }); @@ -113121,6 +116553,7 @@ var ts; } return this.program.getSourceFileByPath(path); }; + /* @internal */ Project.prototype.getSourceFileOrConfigFile = function (path) { var options = this.program.getCompilerOptions(); return path === options.configFilePath ? options.configFile : this.getSourceFile(path); @@ -113128,14 +116561,28 @@ var ts; Project.prototype.close = function () { var _this = this; if (this.program) { + // if we have a program - release all files that are enlisted in program but arent root + // The releasing of the roots happens later + // The project could have pending update remaining and hence the info could be in the files but not in program graph for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } + var projectReferences = this.program.getProjectReferences(); + if (projectReferences) { + for (var _b = 0, projectReferences_2 = projectReferences; _b < projectReferences_2.length; _b++) { + var ref = projectReferences_2[_b]; + if (ref) { + this.detachScriptInfoFromProject(ref.sourceFile.fileName); + } + } + } } + // Release external files ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); }); - for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { - var root = _c[_b]; + // Always remove root files from the project + for (var _c = 0, _d = this.rootFiles; _c < _d.length; _c++) { + var root = _d[_c]; root.detachFromProject(this); } this.projectService.pendingEnsureProjectForOpenFiles = true; @@ -113148,15 +116595,19 @@ var ts; this.resolutionCache = undefined; this.cachedUnresolvedImportsPerFile = undefined; this.directoryStructureHost = undefined; + // Clean up file watchers waiting for missing files if (this.missingFilesMap) { ts.clearMap(this.missingFilesMap, ts.closeFileWatcher); this.missingFilesMap = undefined; } + // signal language service to release source files acquired from document registry this.languageService.dispose(); this.languageService = undefined; }; Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) { var info = this.projectService.getScriptInfo(uncheckedFilename); + // We might not find the script info in case its not associated with the project any more + // and project graph was not updated (eg delayed update graph in case of files changed/deleted on the disk) if (info && !this.isRoot(info)) { info.detachFromProject(this); } @@ -113167,12 +116618,14 @@ var ts; Project.prototype.hasRoots = function () { return this.rootFiles && this.rootFiles.length > 0; }; + /*@internal*/ Project.prototype.isOrphan = function () { return false; }; Project.prototype.getRootFiles = function () { return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); }; + /*@internal*/ Project.prototype.getRootFilesMap = function () { return this.rootFilesMap; }; @@ -113182,6 +116635,7 @@ var ts; Project.prototype.getScriptInfos = function () { var _this = this; if (!this.languageServiceEnabled) { + // if language service is not enabled - return just root files return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { @@ -113198,6 +116652,7 @@ var ts; return []; } if (!this.languageServiceEnabled) { + // if language service is disabled assume that all files in program are root files + default library var rootFiles = this.getRootFiles(); if (this.compilerOptions) { var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); @@ -113252,7 +116707,7 @@ var ts; return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); }; Project.prototype.containsFile = function (filename, requireOpen) { - var info = this.projectService.getScriptInfoForPath(this.toPath(filename)); + var info = this.projectService.getScriptInfoForNormalizedPath(filename); if (info && (info.isScriptOpen() || !requireOpen)) { return this.containsScriptInfo(info); } @@ -113261,6 +116716,7 @@ var ts; Project.prototype.isRoot = function (info) { return this.rootFilesMap && this.rootFilesMap.get(info.path) === info; }; + // add a root file to project Project.prototype.addRoot = function (info) { ts.Debug.assert(!this.isRoot(info)); this.rootFiles.push(info); @@ -113268,6 +116724,7 @@ var ts; info.attachToProject(this); this.markAsDirty(); }; + // add a root file that doesnt exist on host Project.prototype.addMissingFileRoot = function (fileName) { var path = this.projectService.toPath(fileName); this.rootFilesMap.set(path, fileName); @@ -113278,6 +116735,7 @@ var ts; this.removeRoot(info); } if (fileExists) { + // If file is present, just remove the resolutions for the file this.resolutionCache.removeResolutionsOfFile(info.path); } else { @@ -113298,18 +116756,23 @@ var ts; this.dirty = true; } }; + /* @internal */ Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, ambientModules) { var cached = this.cachedUnresolvedImportsPerFile.get(file.path); if (cached) { + // found cached result, return return cached; } var unresolvedImports; if (file.resolvedModules) { file.resolvedModules.forEach(function (resolvedModule, name) { + // pick unresolved non-relative names if (!resolvedModule && !ts.isExternalModuleNameRelative(name) && !isAmbientlyDeclaredModule(name)) { + // for non-scoped names extract part up-to the first slash + // for scoped names - extract up to the second slash var trimmed = name.trim(); var i = trimmed.indexOf("/"); - if (i !== -1 && trimmed.charCodeAt(0) === 64) { + if (i !== -1 && trimmed.charCodeAt(0) === 64 /* at */) { i = trimmed.indexOf("/", i + 1); } if (i !== -1) { @@ -113325,9 +116788,14 @@ var ts; return ambientModules.some(function (m) { return m === name; }); } }; + /* @internal */ Project.prototype.onFileAddedOrRemoved = function () { this.hasAddedorRemovedFiles = true; }; + /** + * Updates set of files that contribute to this project + * @returns: true if set of files in the project stays the same and false - otherwise. + */ Project.prototype.updateGraph = function () { var _a; this.resolutionCache.startRecordingFilesWithChangedResolutions(); @@ -113337,9 +116805,18 @@ var ts; var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { var file = changedFiles_1[_i]; + // delete cached information for changed files this.cachedUnresolvedImportsPerFile.delete(file); } + // update builder only if language service is enabled + // otherwise tell it to drop its internal state if (this.languageServiceEnabled) { + // 1. no changes in structure, no changes in unresolved imports - do nothing + // 2. no changes in structure, unresolved imports were changed - collect unresolved imports for all files + // (can reuse cached imports for files that were not changed) + // 3. new files were added/removed, but compilation settings stays the same - collect unresolved imports for all new/modified files + // (can reuse cached imports for files that were not changed) + // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch if (hasNewProgram || changedFiles.length) { var result = void 0; var ambientModules = this.program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); @@ -113362,12 +116839,16 @@ var ts; } return !hasNewProgram; }; + /*@internal*/ Project.prototype.updateTypingFiles = function (typingFiles) { var _this = this; - ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); }); + ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), + /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); }); this.typingFiles = typingFiles; + // Invalidate files with unresolved imports this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); }; + /* @internal */ Project.prototype.getCurrentProgram = function () { return this.program; }; @@ -113383,11 +116864,14 @@ var ts; var start = ts.timestamp(); this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); this.resolutionCache.startCachingPerDirectoryResolution(); - this.program = this.languageService.getProgram(); + this.program = this.languageService.getProgram(); // TODO: GH#18217 this.dirty = false; this.resolutionCache.finishCachingPerDirectoryResolution(); ts.Debug.assert(oldProgram === undefined || this.program !== undefined); - var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))); + // bump up the version if + // - oldProgram is not set - this is a first time updateGraph is called + // - newProgram is different from the old program and structure of the old program was not reused. + var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2 /* Completely */))); this.hasChangedAutomaticTypeDirectiveNames = false; if (hasNewProgram) { if (oldProgram) { @@ -113396,17 +116880,26 @@ var ts; if (this.program.getSourceFileByPath(f.path)) { continue; } + // new program does not contain this file - detach it from the project this.detachScriptInfoFromProject(f.fileName); } } - ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); }); + // Update the missing file paths watcher + ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), + // Watch the missing files + function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); }); + // Watch the type locations that would be added to program as part of automatic type resolutions if (this.languageServiceEnabled) { this.resolutionCache.updateTypeRootsWatch(); } } var oldExternalFiles = this.externalFiles || server.emptyArray; this.externalFiles = this.getExternalFiles(); - ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), function (inserted) { + ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), + // Ensure a ScriptInfo is created for new external files. This is performed indirectly + // by the LSHost for files in the program when the program is retrieved above but + // the program doesn't contain external files so this must be done explicitly. + function (inserted) { var scriptInfo = _this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, _this.currentDirectory, _this.directoryStructureHost); scriptInfo.attachToProject(_this); }, function (removed) { return _this.detachScriptInfoFromProject(removed); }); @@ -113430,9 +116923,10 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { _this.missingFilesMap.delete(missingFilePath); fileWatcher.close(); + // When a missing file is created, we should update the graph. _this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this); } - }, ts.PollingInterval.Medium, "Missing file from program", this); + }, ts.PollingInterval.Medium, "Missing file from program" /* MissingFilePath */, this); return fileWatcher; }; Project.prototype.isWatchedMissingFile = function (path) { @@ -113455,8 +116949,8 @@ var ts; var sourceFiles = this.program.getSourceFiles(); var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; if (writeProjectFileNames) { - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var file = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { + var file = sourceFiles_9[_i]; strBuilder += "\t" + file.fileName + "\n"; } } @@ -113469,6 +116963,7 @@ var ts; this.compilerOptions = compilerOptions; this.setInternalCompilerOptionsForEmittingJsFiles(); if (ts.changesAffectModuleResolution(oldOptions, compilerOptions)) { + // reset cached unresolved imports if changes in compiler options affected module resolution this.cachedUnresolvedImportsPerFile.clear(); this.lastCachedUnresolvedImportsList = undefined; this.resolutionCache.clear(); @@ -113476,8 +116971,9 @@ var ts; this.markAsDirty(); } }; + /* @internal */ Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - this.updateGraph(); + server.updateProjectIfDirty(this); var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -113488,10 +116984,13 @@ var ts; }; var updatedFileNames = this.updatedFileNames; this.updatedFileNames = undefined; + // check if requested version is the same that we have reported last time if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + // if current structure version is the same - return info without any changes if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) { return { info: info, projectErrors: this.getGlobalProjectErrors() }; } + // compute and return the difference var lastReportedFileNames_1 = this.lastReportedFileNames; var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); var currentFiles_1 = ts.arrayToSet(this.getFileNames().concat(externalFiles)); @@ -113513,6 +117012,7 @@ var ts; return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.getGlobalProjectErrors() }; } else { + // unknown version - return everything var projectFileNames = this.getFileNames(); var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); var allFiles = projectFileNames.concat(externalFiles); @@ -113521,6 +117021,7 @@ var ts; return { info: info, files: allFiles, projectErrors: this.getGlobalProjectErrors() }; } }; + // remove a root file from project Project.prototype.removeRoot = function (info) { ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); @@ -113532,20 +117033,26 @@ var ts; this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } + // Search our peer node_modules, then any globally-specified probe paths + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_1 = function (globalPluginName) { + var _loop_26 = function (globalPluginName) { + // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; + // Skip already-locally-loaded plugins if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; - this_1.projectService.logger.info("Loading global plugin " + globalPluginName); - this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); + // Provide global: true so plugins can detect why they can't find their config + this_2.projectService.logger.info("Loading global plugin " + globalPluginName); + this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); }; - var this_1 = this; + var this_2 = this; + // Enable global plugins with synthetic configuration entries for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_1(globalPluginName); + _loop_26(globalPluginName); } } }; @@ -113565,6 +117072,7 @@ var ts; this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); } }; + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ Project.prototype.refreshDiagnostics = function () { this.projectService.sendProjectsUpdatedInBackgroundEvent(); }; @@ -113601,10 +117109,19 @@ var ts; return Project; }()); server.Project = Project; - var InferredProject = (function (_super) { + /** + * If a file is opened and no tsconfig (or jsconfig) is found, + * the file and its imports/references are put into an InferredProject. + */ + var InferredProject = /** @class */ (function (_super) { __extends(InferredProject, _super); + /*@internal*/ function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory) { - var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, undefined, compilerOptions, false, projectService.host, currentDirectory) || this; + var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, + // TODO: GH#18217 + /*files*/ undefined, + /*lastFileExceededProgramSize*/ undefined, compilerOptions, + /*compileOnSaveEnabled*/ false, projectService.host, currentDirectory) || this; _this._isJsInferredProject = false; _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); if (!projectRootPath && !projectService.useSingleInferredProject) { @@ -113620,6 +117137,7 @@ var ts; } }; InferredProject.prototype.setCompilerOptions = function (options) { + // Avoid manipulating the given options directly var newOptions = options ? ts.cloneCompilerOptions(options) : this.getCompilationSettings(); if (!newOptions) { return; @@ -113637,7 +117155,7 @@ var ts; ts.Debug.assert(info.isScriptOpen()); this.projectService.startWatchingConfigFilesForInferredProjectRoot(info); if (!this._isJsInferredProject && info.isJavaScript()) { - this.toggleJsInferredProject(true); + this.toggleJsInferredProject(/*isJsInferredProject*/ true); } _super.prototype.addRoot.call(this, info); }; @@ -113646,14 +117164,18 @@ var ts; _super.prototype.removeRoot.call(this, info); if (this._isJsInferredProject && info.isJavaScript()) { if (ts.every(this.getRootScriptInfos(), function (rootInfo) { return !rootInfo.isJavaScript(); })) { - this.toggleJsInferredProject(false); + this.toggleJsInferredProject(/*isJsInferredProject*/ false); } } }; + /*@internal*/ InferredProject.prototype.isOrphan = function () { return !this.hasRoots(); }; InferredProject.prototype.isProjectWithSingleRoot = function () { + // - when useSingleInferredProject is not set and projectRootPath is not set, + // we can guarantee that this will be the only root + // - other wise it has single root if it has single root script info return (!this.projectRootPath && !this.projectService.useSingleInferredProject) || this.getRootScriptInfos().length === 1; }; @@ -113680,17 +117202,28 @@ var ts; return InferredProject; }(Project)); server.InferredProject = InferredProject; - var ConfiguredProject = (function (_super) { + /** + * If a file is opened, the server will look for a tsconfig (or jsconfig) + * and if successfull create a ConfiguredProject for it. + * Otherwise it will create an InferredProject. + */ + var ConfiguredProject = /** @class */ (function (_super) { __extends(ConfiguredProject, _super); + /*@internal*/ function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.compileOnSaveEnabled = compileOnSaveEnabled; _this.projectReferences = projectReferences; + /** Ref count to the project when opened from external project */ _this.externalProjectRefCount = 0; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); _this.enablePlugins(); return _this; } + /** + * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph + * @returns: true if set of files in the project stays the same and false - otherwise. + */ ConfiguredProject.prototype.updateGraph = function () { var reloadLevel = this.pendingReload; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; @@ -113704,6 +117237,7 @@ var ts; return _super.prototype.updateGraph.call(this); } }; + /*@internal*/ ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { return this.directoryStructureHost; }; @@ -113711,11 +117245,16 @@ var ts; return server.asNormalizedPath(this.getProjectName()); }; ConfiguredProject.prototype.getProjectReferences = function () { - return this.projectReferences; + return this.projectReferences || server.emptyArray; }; ConfiguredProject.prototype.updateReferences = function (refs) { this.projectReferences = refs; }; + /*@internal*/ + ConfiguredProject.prototype.getResolvedProjectReferences = function () { + var program = this.getCurrentProgram(); + return program && program.getProjectReferences(); + }; ConfiguredProject.prototype.enablePlugins = function () { var host = this.projectService.host; var options = this.getCompilationSettings(); @@ -113723,12 +117262,15 @@ var ts; this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } + // Search our peer node_modules, then any globally-specified probe paths + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.allowLocalPluginLoads) { var local = ts.getDirectoryPath(this.canonicalConfigFilePath); this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths"); searchPaths.unshift(local); } + // Enable tsconfig-specified plugins if (options.plugins) { for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { var pluginConfigEntry = _a[_i]; @@ -113737,9 +117279,15 @@ var ts; } this.enableGlobalPlugins(); }; + /** + * Get the errors that dont have any file name associated + */ ConfiguredProject.prototype.getGlobalProjectErrors = function () { return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; }; + /** + * Get all the project errors + */ ConfiguredProject.prototype.getAllProjectErrors = function () { return this.projectErrors || server.emptyArray; }; @@ -113752,10 +117300,14 @@ var ts; ConfiguredProject.prototype.getTypeAcquisition = function () { return this.typeAcquisition; }; + /*@internal*/ ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) { var _this = this; - ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); }); + ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, + // Create new directory watcher + function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); }); }; + /*@internal*/ ConfiguredProject.prototype.stopWatchingWildCards = function () { if (this.directoriesWatchedForWildcards) { ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf); @@ -113772,44 +117324,62 @@ var ts; this.configFileSpecs = undefined; _super.prototype.close.call(this); }; + /* @internal */ ConfiguredProject.prototype.addExternalProjectReference = function () { this.externalProjectRefCount++; }; + /* @internal */ ConfiguredProject.prototype.deleteExternalProjectReference = function () { this.externalProjectRefCount--; }; + /** Returns true if the project is needed by any of the open script info/external project */ + /* @internal */ ConfiguredProject.prototype.hasOpenRef = function () { var _this = this; if (!!this.externalProjectRefCount) { return true; } + // Closed project doesnt have any reference if (this.isClosed()) { return false; } var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); if (this.projectService.hasPendingProjectUpdate(this)) { + // If there is pending update for this project, + // we dont know if this project would be needed by any of the open files impacted by this config file + // In that case keep the project alive if there are open files impacted by this project return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; } + // If there is no pending update for this project, + // We know exact set of open files that get impacted by this configured project as the files in the project + // The project is referenced only if open files impacted by this project are present in this project return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; }; + /*@internal*/ ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { if (hasFileNames) { - ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); + ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); // TODO: GH#18217 } - else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { + else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { // TODO: GH#18217 this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); } }; return ConfiguredProject; }(Project)); server.ConfiguredProject = ConfiguredProject; - var ExternalProject = (function (_super) { + /** + * Project whose configuration is handled externally, such as in a '.csproj'. + * These are created only if a host explicitly calls `openExternalProject`. + */ + var ExternalProject = /** @class */ (function (_super) { __extends(ExternalProject, _super); + /*@internal*/ function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath) { - var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this; + var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, + /*hasExplicitListOfFiles*/ true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this; _this.externalProjectName = externalProjectName; _this.compileOnSaveEnabled = compileOnSaveEnabled; _this.excludedFiles = []; @@ -113838,7 +117408,11 @@ var ts; var server; (function (server) { server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + /*@internal*/ + server.maxFileSize = 4 * 1024 * 1024; + // tslint:disable variable-name server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; server.ProjectInfoTelemetryEvent = "projectInfo"; @@ -113849,6 +117423,7 @@ var ts; var option = commandLineOptions_1[_i]; if (typeof option.type === "object") { var optionMap = option.type; + // verify that map contains only numbers optionMap.forEach(function (value) { ts.Debug.assert(typeof value === "number"); }); @@ -113863,25 +117438,47 @@ var ts; block: ts.IndentStyle.Block, smart: ts.IndentStyle.Smart }); + /** + * How to understand this block: + * * The 'match' property is a regexp that matches a filename. + * * If 'match' is successful, then: + * * All files from 'exclude' are removed from the project. See below. + * * All 'types' are included in ATA + * * What the heck is 'exclude' ? + * * An array of an array of strings and numbers + * * Each array is: + * * An array of strings and numbers + * * The strings are literals + * * The numbers refer to capture group indices from the 'match' regexp + * * Remember that '1' is the first group + * * These are concatenated together to form a new regexp + * * Filenames matching these regexps are excluded from the project + * This default value is tested in tsserverProjectSystem.ts; add tests there + * if you are changing this so that you can be sure your regexp works! + */ var defaultTypeSafeList = { "jquery": { + // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, types: ["jquery"] }, "WinJS": { + // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, exclude: [["^", 1, "/.*"]], - types: ["winjs"] + types: ["winjs"] // And fetch the @types package for WinJS }, "Kendo": { + // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i, exclude: [["^", 1, "/.*"]], types: ["kendo-ui"] }, "Office Nuget": { + // e.g. /scripts/Office/1/excel-15.debug.js match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, exclude: [["^", 1, "/.*"]], - types: ["office"] + types: ["office"] // @types package to fetch instead }, "References": { match: /^(.*\/_references\.js)$/i, @@ -113913,15 +117510,15 @@ var ts; function convertScriptKindName(scriptKindName) { switch (scriptKindName) { case "JS": - return 1; + return 1 /* JS */; case "JSX": - return 2; + return 2 /* JSX */; case "TS": - return 3; + return 3 /* TS */; case "TSX": - return 4; + return 4 /* TSX */; default: - return 0; + return 0 /* Unknown */; } } server.convertScriptKindName = convertScriptKindName; @@ -113941,7 +117538,7 @@ var ts; }); } } - return result; + return result; // TODO: GH#18217 }, hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, }; @@ -113958,6 +117555,7 @@ var ts; } } } + /* @internal */ var WatchType; (function (WatchType) { WatchType["ConfigFilePath"] = "Config file for the program"; @@ -113978,29 +117576,73 @@ var ts; ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); + function isOpenScriptInfo(infoOrFileName) { + return !!infoOrFileName.containingProjects; + } function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } + /*@internal*/ function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } - var ProjectService = (function () { + server.updateProjectIfDirty = updateProjectIfDirty; + var ProjectService = /** @class */ (function () { function ProjectService(opts) { var _this = this; + /** + * Container of all known scripts + */ this.filenameToScriptInfo = ts.createMap(); + /** + * Contains all the deleted script info's version information so that + * it does not reset when creating script info again + * (and could have potentially collided with version where contents mismatch) + */ + this.filenameToScriptInfoVersion = ts.createMap(); + // Set of all '.js' files ever opened. this.allJsFilesForOpenFileTelemetry = ts.createMap(); + /** + * maps external project file name to list of config files that were the part of this project + */ this.externalProjectToConfiguredProjectMap = ts.createMap(); + /** + * external projects (configuration and list of root files is not controlled by tsserver) + */ this.externalProjects = []; + /** + * projects built from openFileRoots + */ this.inferredProjects = []; + /** + * projects specified by a tsconfig.json file + */ this.configuredProjects = ts.createMap(); + /** + * Open files: with value being project root path, and key being Path of the file that is open + */ this.openFiles = ts.createMap(); + /** + * Map of open files that are opened without complete path but have projectRoot as current directory + */ this.openFilesWithNonRootedDiskPath = ts.createMap(); this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap(); + /** + * Project size for configured or external projects + */ this.projectToSizeMap = ts.createMap(); + /** + * This is a map of config file paths existance that doesnt need query to disk + * - The entry can be present because there is inferred project that needs to watch addition of config file to directory + * In this case the exists could be true/false based on config file is present or not + * - Or it is present if we have configured project open with config file at that location + * In this case the exists property is always true + */ this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; this.legacySafelist = {}; this.pendingProjectUpdates = ts.createMap(); + /** Tracks projects that we have already sent telemetry for. */ this.seenProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; @@ -114036,7 +117678,7 @@ var ts; this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), - preferences: ts.defaultPreferences, + preferences: ts.emptyOptions, hostInfo: "Unknown host", extraFileExtensions: [] }; @@ -114049,26 +117691,33 @@ var ts; ProjectService.prototype.toPath = function (fileName) { return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName); }; + /*@internal*/ ProjectService.prototype.getExecutingFilePath = function () { return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); }; + /*@internal*/ ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) { return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); }; + /*@internal*/ ProjectService.prototype.setDocument = function (key, path, sourceFile) { var info = ts.Debug.assertDefined(this.getScriptInfoForPath(path)); info.cacheSourceFile = { key: key, sourceFile: sourceFile }; }; + /*@internal*/ ProjectService.prototype.getDocument = function (key, path) { var info = this.getScriptInfoForPath(path); return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : undefined; }; + /* @internal */ ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { this.ensureProjectStructuresUptoDate(); }; + /* @internal */ ProjectService.prototype.getCompilerOptionsForInferredProjects = function () { return this.compilerOptionsForInferredProjects; }; + /* @internal */ ProjectService.prototype.onUpdateLanguageServiceStateForProject = function (project, languageServiceEnabled) { if (!this.eventHandler) { return; @@ -114081,16 +117730,18 @@ var ts; }; ProjectService.prototype.loadTypesMap = function () { try { - var fileContent = this.host.readFile(this.typesMapLocation); + var fileContent = this.host.readFile(this.typesMapLocation); // TODO: GH#18217 if (fileContent === undefined) { this.logger.info("Provided types map file \"" + this.typesMapLocation + "\" doesn't exist"); return; } var raw = JSON.parse(fileContent); + // Parse the regexps for (var _i = 0, _a = Object.keys(raw.typesMap); _i < _a.length; _i++) { var k = _a[_i]; raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i"); } + // raw is now fixed and ready this.safelist = raw.typesMap; for (var key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { @@ -114111,10 +117762,12 @@ var ts; } switch (response.kind) { case server.ActionSet: + // Update the typing files and update the project project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); break; case server.ActionInvalidate: - this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, true); + // Do not clear resolution cache, there was changes detected in typings, so enque typing request and let it get us correct results + this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ true); return; } this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); @@ -114122,13 +117775,15 @@ var ts; ProjectService.prototype.delayEnsureProjectForOpenFiles = function () { var _this = this; this.pendingEnsureProjectForOpenFiles = true; - this.throttledOperations.schedule("*ensureProjectForOpenFiles*", 250, function () { + this.throttledOperations.schedule("*ensureProjectForOpenFiles*", /*delay*/ 250, function () { if (_this.pendingProjectUpdates.size !== 0) { _this.delayEnsureProjectForOpenFiles(); } else { if (_this.pendingEnsureProjectForOpenFiles) { _this.ensureProjectForOpenFiles(); + // Send the event to notify that there were background project updates + // send current list of open files _this.sendProjectsUpdatedInBackgroundEvent(); } } @@ -114139,15 +117794,17 @@ var ts; project.markAsDirty(); var projectName = project.getProjectName(); this.pendingProjectUpdates.set(projectName, project); - this.throttledOperations.schedule(projectName, 250, function () { + this.throttledOperations.schedule(projectName, /*delay*/ 250, function () { if (_this.pendingProjectUpdates.delete(projectName)) { - project.updateGraph(); + updateProjectIfDirty(project); } }); }; + /*@internal*/ ProjectService.prototype.hasPendingProjectUpdate = function (project) { return this.pendingProjectUpdates.has(project.getProjectName()); }; + /* @internal */ ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () { var _this = this; if (!this.eventHandler) { @@ -114161,6 +117818,18 @@ var ts; }; this.eventHandler(event); }; + /* @internal */ + ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { + if (!this.eventHandler) { + return; + } + var event = { + eventName: server.LargeFileReferencedEvent, + data: { file: file, fileSize: fileSize, maxFileSize: server.maxFileSize } + }; + this.eventHandler(event); + }; + /* @internal */ ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { this.delayUpdateProjectGraph(project); this.delayEnsureProjectForOpenFiles(); @@ -114177,6 +117846,8 @@ var ts; ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) { ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); var compilerOptions = convertCompilerOptions(projectCompilerOptions); + // always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside + // previously we did not expose a way for user to change these settings and this option was enabled by default compilerOptions.allowNonTsExtensions = true; var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath); if (canonicalProjectRootPath) { @@ -114187,6 +117858,14 @@ var ts; } for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var project = _a[_i]; + // Only update compiler options in the following cases: + // - Inferred projects without a projectRootPath, if the new options do not apply to + // a workspace root + // - Inferred projects with a projectRootPath, if the new options do not apply to a + // workspace root and there is no more specific set of options for that project's + // root path + // - Inferred projects with a projectRootPath, if the new options apply to that + // project root path. if (canonicalProjectRootPath ? project.projectRootPath === canonicalProjectRootPath : !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { @@ -114207,22 +117886,48 @@ var ts; } return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); }; + /* @internal */ + ProjectService.prototype.forEachProject = function (cb) { + this.inferredProjects.forEach(cb); + this.configuredProjects.forEach(cb); + this.externalProjects.forEach(cb); + }; + /* @internal */ + ProjectService.prototype.forEachEnabledProject = function (cb) { + this.forEachProject(function (project) { + if (!project.isOrphan() && project.languageServiceEnabled) { + cb(project); + } + }); + }; ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) { + return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName); + }; + /* @internal */ + ProjectService.prototype.tryGetDefaultProjectForFile = function (fileName) { var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - if (ensureProject && (!scriptInfo || scriptInfo.isOrphan())) { - this.ensureProjectStructuresUptoDate(); - scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - if (!scriptInfo) { - return server.Errors.ThrowNoProject(); - } - return scriptInfo.getDefaultProject(); - } return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined; }; + /* @internal */ + ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) { + return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName); + }; + ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileName) { + this.ensureProjectStructuresUptoDate(); + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo ? scriptInfo.getDefaultProject() : server.Errors.ThrowNoProject(); + }; ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { this.ensureProjectStructuresUptoDate(); return this.getScriptInfo(uncheckedFileName); }; + /** + * Ensures the project structures are upto date + * This means, + * - we go through all the projects and update them if they are dirty + * - if updates reflect some change in structure or there was pending request to ensure projects for open files + * ensure that each open script info has project + */ ProjectService.prototype.ensureProjectStructuresUptoDate = function () { var hasChanges = this.pendingEnsureProjectForOpenFiles; this.pendingProjectUpdates.clear(); @@ -114244,15 +117949,24 @@ var ts; var info = this.getScriptInfoForNormalizedPath(file); return info && info.getPreferences() || this.hostConfiguration.preferences; }; + ProjectService.prototype.getHostFormatCodeOptions = function () { + return this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.getHostPreferences = function () { + return this.hostConfiguration.preferences; + }; ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind, path) { var info = this.getScriptInfoForPath(path); if (!info) { this.logger.msg("Error: got watch notification for unknown file: " + fileName); } else if (eventKind === ts.FileWatcherEventKind.Deleted) { + // File was deleted this.handleDeletedFile(info); } else if (!info.isScriptOpen()) { + // file has been changed which might affect the set of referenced files in projects that include + // this file and set of inferred projects info.delayReloadNonMixedContentFile(); this.delayUpdateProjectGraphs(info.containingProjects); } @@ -114261,58 +117975,87 @@ var ts; this.stopWatchingScriptInfo(info); if (!info.isScriptOpen()) { this.deleteScriptInfo(info); + // capture list of projects since detachAllProjects will wipe out original list var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); + // update projects to make sure that set of referenced files is correct this.delayUpdateProjectGraphs(containingProjects); } }; + /** + * This is to watch whenever files are added or removed to the wildcard directories + */ + /*@internal*/ ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { var _this = this; return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) { var fileOrDirectoryPath = _this.toPath(fileOrDirectory); project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); var configFilename = project.getConfigFilePath(); + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), _this.hostConfiguration.extraFileExtensions)) { _this.logger.info("Project: " + configFilename + " Detected file add/remove of non supported extension: " + fileOrDirectory); return; } + // Reload is pending, do the reload if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) { project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); } - }, flags, "Wild card directory", project); + }, flags, "Wild card directory" /* WildcardDirectories */, project); }; + /** Gets the config file existence info for the configured project */ + /*@internal*/ ProjectService.prototype.getConfigFileExistenceInfo = function (project) { return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); }; ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) { var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); if (eventKind === ts.FileWatcherEventKind.Deleted) { + // Update the cached status + // We arent updating or removing the cached config file presence info as that will be taken care of by + // setConfigFilePresenceByClosedConfigFile when the project is closed (depending on tracking open files) configFileExistenceInfo.exists = false; this.removeProject(project); - this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files"); - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false); + // Reload the configured projects for the open files in the map as they are affected by this config file + // Since the configured project was deleted, we want to reload projects for all the open files including files + // that are not root of the inferred project + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); } else { - this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files"); + this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */); project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; this.delayUpdateProjectGraph(project); - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, true); + // As we scheduled the update on configured project graph, + // we would need to schedule the project reload for only the root of inferred projects + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ true); } }; + /** + * This is the callback function for the config file add/remove/change at any location + * that matters to open script info but doesnt have configured project open + * for the config file + */ ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) { + // This callback is called only if we dont have config file project for this config file var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName); var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath); configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files"); - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); + // Because there is no configured project open for the config file, the tracking open files map + // will only have open files that need the re-detection of the project and hence + // reload projects for all the tracking open files in the map + this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); }; ProjectService.prototype.removeProject = function (project) { this.logger.info("remove project: " + project.getRootFiles().toString()); project.close(); - if (ts.Debug.shouldAssert(1)) { + if (ts.Debug.shouldAssert(1 /* Normal */)) { this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project)); }); } + // Remove the project from pending project updates this.pendingProjectUpdates.delete(project.getProjectName()); switch (project.projectKind) { case server.ProjectKind.External: @@ -114329,6 +118072,7 @@ var ts; break; } }; + /*@internal*/ ProjectService.prototype.assignOrphanScriptInfoToInferredProject = function (info, projectRootPath) { ts.Debug.assert(info.isOrphan()); var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || @@ -114336,30 +118080,47 @@ var ts; this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? this.currentDirectory : ts.getDirectoryPath(info.path)); project.addRoot(info); if (info.containingProjects[0] !== project) { + // Ensure this is first project, we could be in this scenario because info could be part of orphan project info.detachFromProject(project); info.containingProjects.unshift(project); } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_2 = function (inferredProject) { + var _loop_27 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } + // Remove the inferred project if the root of it is now part of newly created inferred project + // e.g through references + // Which means if any root of inferred project is part of more than 1 project can be removed + // This logic is same as iterating over all open files and calling + // this.removeRootOfInferredProjectIfNowPartOfOtherProject(f); + // Since this is also called from refreshInferredProject and closeOpen file + // to update inferred projects of the open file, this iteration might be faster + // instead of scanning all open files var roots = inferredProject.getRootScriptInfos(); ts.Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath); if (roots.length === 1 && ts.forEach(roots[0].containingProjects, function (p) { return p !== roots[0].containingProjects[0] && !p.isOrphan(); })) { - inferredProject.removeFile(roots[0], true, true); + inferredProject.removeFile(roots[0], /*fileExists*/ true, /*detachFromProject*/ true); } }; + // Note that we need to create a copy of the array since the list of project can change for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_2(inferredProject); + _loop_27(inferredProject); } } return project; }; + /** + * Remove this file from the set of open, non-configured files. + * @param info The file that has been closed or newly configured + */ ProjectService.prototype.closeOpenFile = function (info) { var _this = this; + // Closing file should trigger re-reading the file content from disk. This is + // because the user may chose to discard the buffer content before saving + // to the disk, and the server's version of the file can be out of sync. var fileExists = this.host.fileExists(info.fileName); info.close(fileExists); this.stopWatchingConfigFilesForClosedScriptInfo(info); @@ -114367,6 +118128,7 @@ var ts; if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) { this.openFilesWithNonRootedDiskPath.delete(canonicalFileName); } + // collect all projects that should be removed var ensureProjectsForOpenFiles = false; for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; @@ -114374,26 +118136,41 @@ var ts; if (info.hasMixedContent) { info.registerFileUpdate(); } + // Do not remove the project so that we can reuse this project + // if it would need to be re-created with next file open } else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { + // If this was the last open root file of inferred project if (p.isProjectWithSingleRoot()) { ensureProjectsForOpenFiles = true; } - p.removeFile(info, fileExists, true); + p.removeFile(info, fileExists, /*detachFromProject*/ true); + // Do not remove the project even if this was last root of the inferred project + // so that we can reuse this project, if it would need to be re-created with next file open } if (!p.languageServiceEnabled) { + // if project language service is disabled then we create a program only for open files. + // this means that project should be marked as dirty to force rebuilding of the program + // on the next request p.markAsDirty(); } } this.openFiles.delete(info.path); if (ensureProjectsForOpenFiles) { + // collect orphaned files and assign them to inferred project just like we treat open of a file this.openFiles.forEach(function (projectRootPath, path) { var info = _this.getScriptInfoForPath(path); + // collect all orphaned script infos from open files if (info.isOrphan()) { _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); } }); } + // Cleanup script infos that arent part of any project (eg. those could be closed script infos not referenced by any project) + // is postponed to next file open so that if file from same project is opened, + // we wont end up creating same script infos + // If the current info is being just closed - add the watcher file to track changes + // But if file was deleted, handle that part if (fileExists) { this.watchClosedScriptInfo(info); } @@ -114403,46 +118180,65 @@ var ts; }; ProjectService.prototype.deleteScriptInfo = function (info) { this.filenameToScriptInfo.delete(info.path); + this.filenameToScriptInfoVersion.set(info.path, info.getVersion()); var realpath = info.getRealpathIfDifferent(); if (realpath) { - this.realpathToScriptInfos.remove(realpath, info); + this.realpathToScriptInfos.remove(realpath, info); // TODO: GH#18217 } }; ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { - if (!configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + // By default the info would get impacted by presence of config file since its in the detection path + // Only adding the info as a root to inferred project will need the existence to be watched by file watcher + if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file"); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); } return configFileExistenceInfo.exists; } - var openFilesImpactedByConfigFile = ts.createMap(); - openFilesImpactedByConfigFile.set(info.path, false); + // Theoretically we should be adding watch for the directory here itself. + // In practice there will be very few scenarios where the config file gets added + // somewhere inside the another config file directory. + // And technically we could handle that case in configFile's directory watcher in some cases + // But given that its a rare scenario it seems like too much overhead. (we werent watching those directories earlier either) + // So what we are now watching is: configFile if the configured project corresponding to it is open + // Or the whole chain of config files for the roots of the inferred projects + // Cache the host value of file exists and add the info to map of open files impacted by this config file var exists = this.host.fileExists(configFileName); + var openFilesImpactedByConfigFile = ts.createMap(); + if (isOpenScriptInfo(info)) { + openFilesImpactedByConfigFile.set(info.path, false); + } configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile }; this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file"); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); return exists; }; ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); if (configFileExistenceInfo) { ts.Debug.assert(configFileExistenceInfo.exists); + // close existing watcher if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { var configFileName = project.getConfigFilePath(); configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; - this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback"); + this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); } } else { + // We could be in this scenario if project is the configured project tracked by external project + // Since that route doesnt check if the config file is present or not this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, { exists: true, openFilesImpactedByConfigFile: ts.createMap() }); } }; + /** + * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project + */ ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) { return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; }); }; @@ -114451,12 +118247,16 @@ var ts; ts.Debug.assert(!!configFileExistenceInfo); if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { var configFileName = closedProject.getConfigFilePath(); + // If there are open files that are impacted by this config file existence + // but none of them are root of inferred project, the config file watcher will be + // created when any of the script infos are added as root of inferred project if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo); } } else { + // There is not a single file open thats tracking the status of this config file. Remove from cache this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath); } }; @@ -114473,25 +118273,36 @@ var ts; }); var watches = []; if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { - watches.push("Config file for the inferred project root"); + watches.push("Config file for the inferred project root" /* ConfigFileForInferredRoot */); } if (this.configuredProjects.has(canonicalConfigFilePath)) { - watches.push("Config file for the program"); + watches.push("Config file for the program" /* ConfigFilePath */); } this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status); }; + /** + * Create the watcher for the configFileExistenceInfo + */ ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) { var _this = this; - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root"); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback"); + configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root" /* ConfigFileForInferredRoot */); + this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); }; + /** + * Close the config file watcher in the cached ConfigFileExistenceInfo + * if there arent any open files that are root of inferred project + */ ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) { + // Close the config file watcher if there are no more open files that are root of inferred project if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject && !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; } }; + /** + * This is called on file close, so that we stop watching the config file for this script info + */ ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) { var _this = this; ts.Debug.assert(!info.isScriptOpen()); @@ -114499,11 +118310,18 @@ var ts; var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path); + // Delete the info from map, since this file is no more open configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path); - _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file"); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file" /* OpenFilesImpactedByConfigFileRemove */); + // If the script info was not root of inferred project, + // there wont be config file watch open because of this script info if (infoIsRootOfInferredProject) { + // But if it is a root, it could be the last script info that is root of inferred project + // and hence we would need to close the config file watcher _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); } + // If there are no open files that are impacted by configFileExistenceInfo after closing this script info + // there is no configured project present, remove the cached existence info if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size && !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); @@ -114512,47 +118330,69 @@ var ts; } }); }; + /** + * This is called by inferred project whenever script info is added as a root + */ + /* @internal */ ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info) { var _this = this; ts.Debug.assert(info.isScriptOpen()); this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo) { + // Create the cache configFileExistenceInfo = { exists: _this.host.fileExists(configFileName), openFilesImpactedByConfigFile: ts.createMap() }; _this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); } + // Set this file as the root of inferred project configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true); - _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root"); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root" /* RootOfInferredProjectTrue */); + // If there is no configured project for this config file, add the file watcher if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject && !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { _this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); } }); }; + /** + * This is called by inferred project whenever root script info is removed from it + */ + /* @internal */ ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) { var _this = this; this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { ts.Debug.assert(info.isScriptOpen()); + // Info is not root of inferred project any more configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); - _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root"); + _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root" /* RootOfInferredProjectFalse */); + // Close the config file watcher _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); } }); }; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ ProjectService.prototype.forEachConfigFileLocation = function (info, action) { var _this = this; if (this.syntaxOnly) { return undefined; } - ts.Debug.assert(this.openFiles.has(info.path)); + ts.Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path)); var projectRootPath = this.openFiles.get(info.path); var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName)); var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); }; + // If projectRootPath doesn't contain info.path, then do normal search for config file var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot(); do { var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); @@ -114574,9 +118414,20 @@ var ts; } while (anySearchPathOk || isSearchPathInProjectRoot()); return undefined; }; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + * If script info is passed in, it is asserted to be open script info + * otherwise just file name + */ ProjectService.prototype.getConfigFileNameForFile = function (info) { var _this = this; - ts.Debug.assert(info.isScriptOpen()); + if (isOpenScriptInfo(info)) + ts.Debug.assert(info.isScriptOpen()); this.logger.info("Search path: " + ts.getDirectoryPath(info.fileName)); var configFileName = this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { return _this.configFileExists(configFileName, canonicalConfigFilePath, info); @@ -114621,6 +118472,7 @@ var ts; this.logger.endGroup(); }; ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { + // make sure that casing of config file name is consistent var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); }; @@ -114632,13 +118484,15 @@ var ts; }; ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); + var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 var result = ts.parseJsonText(configFilename, configFileContent); if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 }; + result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; } var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), + /*existingOptions*/ {}, configFilename, + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); if (parsedCommandLine.errors.length) { errors.push.apply(errors, parsedCommandLine.errors); } @@ -114657,6 +118511,7 @@ var ts; }; return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; }; + /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { return; @@ -114665,8 +118520,8 @@ var ts; this.projectToSizeMap.set(name, 0); this.projectToSizeMap.forEach(function (val) { return (availableSpace -= (val || 0)); }); var totalNonTsFileSize = 0; - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var f = fileNames_1[_i]; + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var f = fileNames_2[_i]; var fileName = propertyReader.getFileName(f); if (ts.hasTypeScriptFileExtension(fileName)) { continue; @@ -114674,6 +118529,7 @@ var ts; totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + // Keep the size as zero since it's disabled return fileName; } } @@ -114687,14 +118543,15 @@ var ts; var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) .filter(function (name) { return hasTypeScriptFileExtension(name); }) - .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) + .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217 .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); } }; ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) { var compilerOptions = convertCompilerOptions(options); - var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, + /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); project.excludedFiles = excludedFiles; this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); @@ -114729,7 +118586,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; + var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; // TODO: GH#18217 return server.getBaseConfigFileName(configFilePath) || "other"; } function convertTypeAcquisition(_a) { @@ -114744,23 +118601,26 @@ var ts; ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { this.updateNonInferredProjectFiles(project, files, propertyReader); project.setTypeAcquisition(typeAcquisition); + // This doesnt need scheduling since its either creation or reload of the project project.updateGraph(); }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; - var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217 var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, // TODO: GH#18217 + lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); project.configFileSpecs = configFileSpecs; - project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program", project); + // TODO: We probably should also watch the configFiles that are extended + project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); + project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 } project.setProjectErrors(configFileErrors); var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); + this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); // TODO: GH#18217 this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); this.sendProjectTelemetry(configFileName, project, projectOptions); @@ -114769,18 +118629,19 @@ var ts; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = ts.createMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var f = files_1[_i]; + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; var newRootFile = propertyReader.getFileName(f); var normalizedPath = server.toNormalizedPath(newRootFile); var isDynamic = server.isDynamicFileName(normalizedPath); var scriptInfo = void 0; var path = void 0; + // Use the project's fileExists so that it can use caching instead of reaching to disk for the query if (!isDynamic && !project.fileExists(newRootFile)) { path = server.normalizedPathToPath(normalizedPath, this.currentDirectory, this.toCanonicalFileName); var existingValue = projectRootFilesMap.get(path); if (server.isScriptInfo(existingValue)) { - project.removeFile(existingValue, false, true); + project.removeFile(existingValue, /*fileExists*/ false, /*detachFromProject*/ true); } projectRootFilesMap.set(path, normalizedPath); scriptInfo = normalizedPath; @@ -114788,22 +118649,27 @@ var ts; else { var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); + scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); // TODO: GH#18217 path = scriptInfo.path; + // If this script info is not already a root add it if (!project.isRoot(scriptInfo)) { project.addRoot(scriptInfo); if (scriptInfo.isScriptOpen()) { + // if file is already root in some inferred project + // - remove the file from that project and delete the project if necessary this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo); } } } newRootScriptInfoMap.set(path, scriptInfo); } + // project's root file map size is always going to be same or larger than new roots map + // as we have already all the new files to the project if (projectRootFilesMap.size > newRootScriptInfoMap.size) { projectRootFilesMap.forEach(function (value, path) { if (!newRootScriptInfoMap.has(path)) { if (server.isScriptInfo(value)) { - project.removeFile(value, project.fileExists(path), true); + project.removeFile(value, project.fileExists(path), /*detachFromProject*/ true); } else { projectRootFilesMap.delete(path); @@ -114811,51 +118677,69 @@ var ts; } }); } + // Just to ensure that even if root files dont change, the changes to the non root file are picked up, + // mark the project as dirty unconditionally project.markAsDirty(); }; ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); + // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently + // therefore if it is undefined, it should not be updated. if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; + /** + * Reload the file names from config file specs and update the project graph + */ + /*@internal*/ ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { - var configFileSpecs = project.configFileSpecs; + var configFileSpecs = project.configFileSpecs; // TODO: GH#18217 var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); return project.updateGraph(); }; + /** + * Read the config file of the project again and update the project + */ + /* @internal */ ProjectService.prototype.reloadConfiguredProject = function (project) { + // At this point, there is no reason to not have configFile in the host var host = project.getCachedDirectoryStructureHost(); + // Clear the cache since we are reloading the project from disk host.clearCache(); var configFileName = project.getConfigFilePath(); this.logger.info("Reloading configured project " + configFileName); + // Read updated contents from disk var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; + // Update the project project.configFileSpecs = configFileSpecs; project.setProjectErrors(configFileErrors); project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 if (lastFileExceededProgramSize) { project.disableLanguageService(lastFileExceededProgramSize); project.stopWatchingWildCards(); } else { project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); + project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); // TODO: GH#18217 this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { if (!this.eventHandler || this.suppressDiagnosticEvents) { return; } + var diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); + diagnostics.push.apply(diagnostics, project.getAllProjectErrors()); this.eventHandler({ eventName: server.ConfigFileDiagEvent, - data: { configFileName: project.getConfigFilePath(), diagnostics: project.getAllProjectErrors(), triggerFile: triggerFile } + data: { configFileName: project.getConfigFilePath(), diagnostics: diagnostics, triggerFile: triggerFile } }); }; ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { @@ -114864,21 +118748,28 @@ var ts; } if (projectRootPath) { var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath); + // if we have an explicit project root path, find (or create) the matching inferred project. for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var project = _a[_i]; if (project.projectRootPath === canonicalProjectRootPath) { return project; } } - return this.createInferredProject(projectRootPath, false, projectRootPath); + return this.createInferredProject(projectRootPath, /*isSingleInferredProject*/ false, projectRootPath); } + // we don't have an explicit root path, so we should try to find an inferred project + // that more closely contains the file. var bestMatch; for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) { var project = _c[_b]; + // ignore single inferred projects (handled elsewhere) if (!project.projectRootPath) continue; + // ignore inferred projects that don't contain the root's path if (!ts.containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) continue; + // ignore inferred projects that are higher up in the project root. + // TODO(rbuckton): Should we add the file as a root to these as well? if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) continue; bestMatch = project; @@ -114889,14 +118780,24 @@ var ts; if (!this.useSingleInferredProject) { return undefined; } + // If `useInferredProjectPerProjectRoot` is not enabled, then there will only be one + // inferred project for all files. If `useInferredProjectPerProjectRoot` is enabled + // then we want to put all files that are not opened with a `projectRootPath` into + // the same inferred project. + // + // To avoid the cost of searching through the array and to optimize for the case where + // `useInferredProjectPerProjectRoot` is not enabled, we will always put the inferred + // project for non-rooted files at the front of the array. if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) { return this.inferredProjects[0]; } - return this.createInferredProject(undefined, true); + // Single inferred project does not have a project root and hence no current directory + return this.createInferredProject(/*currentDirectory*/ undefined, /*isSingleInferredProject*/ true); }; ProjectService.prototype.getOrCreateSingleInferredWithoutProjectRoot = function (currentDirectory) { ts.Debug.assert(!this.useSingleInferredProject); var expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory || "")); + // Reuse the project with same current directory but no roots for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; if (!inferredProject.projectRootPath && @@ -114918,12 +118819,28 @@ var ts; } return project; }; + /*@internal*/ ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClient = function (uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) { - return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, undefined, undefined, hostToQueryFileExistsOn); + return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, /*scriptKind*/ undefined, + /*hasMixedContent*/ undefined, hostToQueryFileExistsOn); }; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; + /* @internal */ + ProjectService.prototype.getScriptInfoOrConfig = function (uncheckedFileName) { + var path = server.toNormalizedPath(uncheckedFileName); + var info = this.getScriptInfoForNormalizedPath(path); + if (info) + return info; + var configProject = this.configuredProjects.get(uncheckedFileName); + return configProject && configProject.getCompilerOptions().configFile; + }; + /** + * Returns the projects that contain script info through SymLink + * Note that this does not return projects in info.containingProjects + */ + /*@internal*/ ProjectService.prototype.getSymlinkedProjects = function (info) { var projects; if (this.realpathToScriptInfos) { @@ -114936,7 +118853,8 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_3 = function (project) { + var _loop_28 = function (project) { + // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && !project.getCompilerOptions().preserveSymlinks && @@ -114952,7 +118870,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_3(project); + _loop_28(project); } } } @@ -114960,11 +118878,13 @@ var ts; ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; ts.Debug.assert(!info.fileWatcher); + // do not watch files with mixed content - server doesn't know how to interpret it + // do not watch files in the global cache location if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { var fileName = info.fileName; - info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); } }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { @@ -114974,10 +118894,10 @@ var ts; } }; ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { - return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, false, undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); }; ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) { - return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, true, fileContent, scriptKind, hasMixedContent); + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ true, fileContent, scriptKind, hasMixedContent); }; ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); @@ -114992,19 +118912,24 @@ var ts; ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info"; }); ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); + // If the file is not opened by client and the file doesnot exist on the disk, return if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; } - info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path); + info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path)); // TODO: GH#18217 this.filenameToScriptInfo.set(info.path, info); + this.filenameToScriptInfoVersion.delete(info.path); if (!openedByClient) { this.watchClosedScriptInfo(info); } else if (!ts.isRootedDiskPath(fileName) && currentDirectory !== this.currentDirectory) { + // File that is opened by user but isn't rooted disk path this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); } } if (openedByClient && !info.isScriptOpen()) { + // Opening closed script info + // either it was created just now, or was part of projects but was closed this.stopWatchingScriptInfo(info); info.open(fileContent); if (hasMixedContent) { @@ -115016,6 +118941,9 @@ var ts; } return info; }; + /** + * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred + */ ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { return !ts.isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName)); @@ -115045,6 +118973,8 @@ var ts; } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + // We need to update the project structures again as it is possible that existing + // project structure could have more or less files depending on extensions permitted this.reloadProjects(); this.logger.info("Host file extension mappings updated"); } @@ -115053,26 +118983,51 @@ var ts; ProjectService.prototype.closeLog = function () { this.logger.close(); }; + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ ProjectService.prototype.reloadProjects = function () { this.logger.info("reload projects."); - this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue); + // If we want this to also reload open files from disk, we could do that, + // but then we need to make sure we arent calling this function + // (and would separate out below reloading of projects to be called when immediate reload is needed) + // as there is no need to load contents of the files from the disk + // Reload Projects + this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue); this.ensureProjectForOpenFiles(); }; ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { - this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, true, ignoreIfNotRootOfInferredProject ? - function (isRootOfInferredProject) { return isRootOfInferredProject; } : - ts.returnTrue); + // Get open files to reload projects for + this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, + /*delayReload*/ true, ignoreIfNotRootOfInferredProject ? + function (isRootOfInferredProject) { return isRootOfInferredProject; } : // Reload open files if they are root of inferred project + ts.returnTrue // Reload all the open files impacted by config file + ); this.delayEnsureProjectForOpenFiles(); }; + /** + * This function goes through all the openFiles and tries to file the config file for them. + * If the config file is found and it refers to existing project, it reloads it either immediately + * or schedules it for reload depending on delayReload option + * If the there is no existing project it just opens the configured project for the config file + * reloadForInfo provides a way to filter out files to reload configured project for + */ ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor) { var _this = this; var updatedProjects = ts.createMap(); + // try to reload config file for all open files openFiles.forEach(function (openFileValue, path) { + // Filter out the files that need to be ignored if (!shouldReloadProjectFor(openFileValue)) { return; } - var info = _this.getScriptInfoForPath(path); + var info = _this.getScriptInfoForPath(path); // TODO: GH#18217 ts.Debug.assert(info.isScriptOpen()); + // This tries to search for a tsconfig.json for the given file. If we found it, + // we first detect if there is already a configured project created for it: if so, + // we re- read the tsconfig file content and update the project only if we havent already done so + // otherwise we create a new one. var configFileName = _this.getConfigFileNameForFile(info); if (configFileName) { var project = _this.findConfiguredProjectByProjectName(configFileName); @@ -115093,26 +119048,51 @@ var ts; } }); }; + /** + * Remove the root of inferred project if script info is part of another project + */ ProjectService.prototype.removeRootOfInferredProjectIfNowPartOfOtherProject = function (info) { + // If the script info is root of inferred project, it could only be first containing project + // since info is added as root to the inferred project only when there are no other projects containing it + // So when it is root of the inferred project and after project structure updates its now part + // of multiple project it needs to be removed from that inferred project because: + // - references in inferred project supercede the root part + // - root / reference in non - inferred project beats root in inferred project + // eg. say this is structure /a/b/a.ts /a/b/c.ts where c.ts references a.ts + // When a.ts is opened, since there is no configured project/external project a.ts can be part of + // a.ts is added as root to inferred project. + // Now at time of opening c.ts, c.ts is also not aprt of any existing project, + // so it will be added to inferred project as a root. (for sake of this example assume single inferred project is false) + // So at this poing a.ts is part of first inferred project and second inferred project (of which c.ts is root) + // And hence it needs to be removed from the first inferred project. ts.Debug.assert(info.containingProjects.length > 0); var firstProject = info.containingProjects[0]; if (!firstProject.isOrphan() && firstProject.projectKind === server.ProjectKind.Inferred && firstProject.isRoot(info) && ts.forEach(info.containingProjects, function (p) { return p !== firstProject && !p.isOrphan(); })) { - firstProject.removeFile(info, true, true); + firstProject.removeFile(info, /*fileExists*/ true, /*detachFromProject*/ true); } }; + /** + * This function is to update the project structure for every inferred project. + * It is called on the premise that all the configured projects are + * up to date. + * This will go through open files and assign them to inferred project if open file is not part of any other project + * After that all the inferred project graphs are updated + */ ProjectService.prototype.ensureProjectForOpenFiles = function () { var _this = this; this.logger.info("Structure before ensureProjectForOpenFiles:"); this.printProjects(); this.openFiles.forEach(function (projectRootPath, path) { var info = _this.getScriptInfoForPath(path); + // collect all orphaned script infos from open files if (info.isOrphan()) { _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); } else { + // Or remove the root of inferred project if is referenced in more than one projects _this.removeRootOfInferredProjectIfNowPartOfOtherProject(info); } }); @@ -115121,12 +119101,55 @@ var ts; this.logger.info("Structure after ensureProjectForOpenFiles:"); this.printProjects(); }; + /** + * Open file whose contents is managed by the client + * @param filename is absolute pathname + * @param fileContent is a known version of the file content that is more up to date than the one on disk + */ ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { - return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); + }; + /*@internal*/ + ProjectService.prototype.getOriginalLocationEnsuringConfiguredProject = function (project, location) { + var originalLocation = project.getSourceMapper().tryGetOriginalLocation(location); + if (!originalLocation) + return undefined; + var fileName = originalLocation.fileName; + if (!this.getScriptInfo(fileName) && !this.host.fileExists(fileName)) + return undefined; + var originalFileInfo = { fileName: server.toNormalizedPath(fileName), path: this.toPath(fileName) }; + var configFileName = this.getConfigFileNameForFile(originalFileInfo); + if (!configFileName) + return undefined; + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + updateProjectIfDirty(configuredProject); + // Keep this configured project as referenced from project + addOriginalConfiguredProject(configuredProject); + var originalScriptInfo = this.getScriptInfo(fileName); + if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) + return undefined; + // Add configured projects as referenced + originalScriptInfo.containingProjects.forEach(function (project) { + if (project.projectKind === server.ProjectKind.Configured) { + addOriginalConfiguredProject(project); + } + }); + return originalLocation; + function addOriginalConfiguredProject(originalProject) { + if (!project.originalConfiguredProjects) { + project.originalConfiguredProjects = ts.createMap(); + } + project.originalConfiguredProjects.set(originalProject.canonicalConfigFilePath, true); + } + }; + /** @internal */ + ProjectService.prototype.fileExists = function (fileName) { + return this.filenameToScriptInfo.has(fileName) || this.host.fileExists(fileName); }; ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) { return ts.find(this.externalProjects, function (proj) { - proj.updateGraph(); + // Ensure project structure is up-to-date to check if info is present in external project + updateProjectIfDirty(proj); return proj.containsScriptInfo(info); }); }; @@ -115134,16 +119157,18 @@ var ts; var _this = this; var configFileName; var configFileErrors; - var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); + var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217 this.openFiles.set(info.path, projectRootPath); var project = this.findExternalProjectContainingOpenScriptInfo(info); - if (!project && !this.syntaxOnly) { + if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization configFileName = this.getConfigFileNameForFile(info); if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { project = this.createConfiguredProject(configFileName); + // Send the event only if the project got created as part of this open request and info is part of the project if (info.isOrphan()) { + // Since the file isnt part of configured project, do not send config file info configFileName = undefined; } else { @@ -115152,28 +119177,42 @@ var ts; } } else { + // Ensure project is ready to check if it contains opened script info updateProjectIfDirty(project); } } } + // Project we have at this point is going to be updated since its either found through + // - external project search, which updates the project before checking if info is present in it + // - configured project - either created or updated to ensure we know correct status of info + // At this point we need to ensure that containing projects of the info are uptodate + // This will ensure that later question of info.isOrphan() will return correct answer + // and we correctly create inferred project for the info info.containingProjects.forEach(updateProjectIfDirty); + // At this point if file is part of any any configured or external project, then it would be present in the containing projects + // So if it still doesnt have any containing projects, it needs to be part of inferred project if (info.isOrphan()) { this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); } ts.Debug.assert(!info.isOrphan()); - this.configuredProjects.forEach(function (project) { - if (!project.hasOpenRef()) { - _this.removeProject(project); - } - }); + // This was postponed from closeOpenFile to after opening next file, + // so that we can reuse the project if we need to right away + this.removeOrphanConfiguredProjects(); + // Remove orphan inferred projects now that we have reused projects + // We need to create a duplicate because we cant guarantee order after removal for (var _i = 0, _a = this.inferredProjects.slice(); _i < _a.length; _i++) { var inferredProject = _a[_i]; if (inferredProject.isOrphan()) { this.removeProject(inferredProject); } } + // Delete the orphan files here because there might be orphan script infos (which are not part of project) + // when some file/s were closed which resulted in project removal. + // It was then postponed to cleanup these script infos so that they can be reused if + // the file from that old project is reopened because of opening file from here. this.filenameToScriptInfo.forEach(function (info) { if (!info.isScriptOpen() && info.isOrphan()) { + // if there are not projects that include this script info - delete it _this.stopWatchingScriptInfo(info); _this.deleteScriptInfo(info); } @@ -115182,6 +119221,42 @@ var ts; this.telemetryOnOpenFile(info); return { configFileName: configFileName, configFileErrors: configFileErrors }; }; + ProjectService.prototype.removeOrphanConfiguredProjects = function () { + var _this = this; + var toRemoveConfiguredProjects = ts.cloneMap(this.configuredProjects); + // Do not remove configured projects that are used as original projects of other + this.inferredProjects.forEach(markOriginalProjectsAsUsed); + this.externalProjects.forEach(markOriginalProjectsAsUsed); + this.configuredProjects.forEach(function (project) { + // If project has open ref (there are more than zero references from external project/open file), keep it alive as well as any project it references + if (project.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + markOriginalProjectsAsUsed(project); + } + else { + // If the configured project for project reference has more than zero references, keep it alive + var resolvedProjectReferences = project.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { + var ref = resolvedProjectReferences_1[_i]; + if (ref) { + var refProject = _this.configuredProjects.get(ref.sourceFile.path); + if (refProject && refProject.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); + } + } + } + } + } + }); + // Remove all the non marked projects + toRemoveConfiguredProjects.forEach(function (project) { return _this.removeProject(project); }); + function markOriginalProjectsAsUsed(project) { + if (!project.isOrphan() && project.originalConfiguredProjects) { + project.originalConfiguredProjects.forEach(function (_value, configuredProjectPath) { return toRemoveConfiguredProjects.delete(configuredProjectPath); }); + } + } + }; ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) { if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { return; @@ -115189,6 +119264,10 @@ var ts; var info = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path).checkJsDirective }; this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } }); }; + /** + * Close file whose contents is managed by the client + * @param filename is absolute pathname + */ ProjectService.prototype.closeClientFile = function (uncheckedFileName) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); if (info) { @@ -115197,15 +119276,16 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_4 = function (proj) { + var _loop_29 = function (proj) { var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_4(proj); + _loop_29(proj); } }; + /* @internal */ ProjectService.prototype.synchronizeProjectList = function (knownProjects) { var files = []; this.collectChanges(knownProjects, this.externalProjects, files); @@ -115213,6 +119293,7 @@ var ts; this.collectChanges(knownProjects, this.inferredProjects, files); return files; }; + /* @internal */ ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { if (openFiles) { for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { @@ -115220,7 +119301,7 @@ var ts; var scriptInfo = this.getScriptInfo(file.fileName); 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); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); // TODO: GH#18217 } } if (changedFiles) { @@ -115238,7 +119319,9 @@ var ts; } } }; + /* @internal */ ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) { + // apply changes in reverse order for (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); @@ -115265,6 +119348,7 @@ var ts; this.externalProjectToConfiguredProjectMap.delete(fileName); } else { + // close external project var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); if (externalProject) { this.removeProject(externalProject); @@ -115273,6 +119357,7 @@ var ts; }; ProjectService.prototype.openExternalProjects = function (projects) { var _this = this; + // record project list before the update var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; }); ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) { projectsToClose.set(externalProjectName, true); @@ -115280,8 +119365,10 @@ var ts; for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { var externalProject = projects_4[_i]; this.openExternalProject(externalProject); + // delete project that is present in input list projectsToClose.delete(externalProject.projectFileName); } + // close projects that were missing in the input list ts.forEachKey(projectsToClose, function (externalProjectName) { _this.closeExternalProject(externalProjectName); }); @@ -115297,6 +119384,7 @@ var ts; var rootFiles = proj.rootFiles; var typeAcquisition = proj.typeAcquisition; ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); + // If type acquisition has been explicitly disabled, do not exclude anything from the project if (typeAcquisition.enable === false) { return []; } @@ -115304,31 +119392,38 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_5 = function (name) { - var rule = this_2.safelist[name]; + var _loop_30 = function (name) { + var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; if (rule.match.test(root)) { - this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'"); + this_3.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'"); + // If the file matches, collect its types packages and exclude rules if (rule.types) { for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { var type = _b[_a]; + // Best-effort de-duping here - doesn't need to be unduplicated but + // we don't want the list to become a 400-element array of just 'kendo' if (typeAcqInclude.indexOf(type) < 0) { typeAcqInclude.push(type); } } } if (rule.exclude) { - var _loop_7 = function (exclude) { + var _loop_32 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { groups[_i] = arguments[_i]; } return exclude.map(function (groupNumberOrString) { + // RegExp group numbers are 1-based, but the first element in groups + // is actually the original string, so it all works out in the end. if (typeof groupNumberOrString === "number") { if (!ts.isString(groups[groupNumberOrString])) { + // Specification was wrong - exclude nothing! _this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups"); + // * can't appear in a filename; escape it because it's feeding into a RegExp return "\\*"; } return ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]); @@ -115342,10 +119437,11 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_7(exclude); + _loop_32(exclude); } } else { + // If not rules listed, add the default rule to exclude the matched file var escaped = ProjectService.escapeFilenameForRegex(root); if (excludeRules.indexOf(escaped) < 0) { excludeRules.push(escaped); @@ -115354,14 +119450,14 @@ var ts; } } }; - var this_2 = this; + var this_3 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_5(name); + _loop_30(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_6 = function (i) { + var _loop_31 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -115372,11 +119468,14 @@ var ts; if (ts.fileExtensionIs(baseName, "js")) { var inferredTypingName = ts.removeFileExtension(baseName); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - if (this_3.legacySafelist[cleanedTypingName]) { - this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); + if (this_4.legacySafelist[cleanedTypingName]) { + this_4.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); excludedFiles.push(normalizedNames[i]); + // *exclude* it from the project... exclude = true; - var typeName = this_3.legacySafelist[cleanedTypingName]; + // ... but *include* it in the list of types to acquire + var typeName = this_4.legacySafelist[cleanedTypingName]; + // Same best-effort dedupe as above if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); } @@ -115384,6 +119483,7 @@ var ts; } } if (!exclude) { + // Exclude any minified files that get this far if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) { excludedFiles.push(normalizedNames[i]); } @@ -115393,14 +119493,16 @@ var ts; } } }; - var this_3 = this; + var this_4 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_6(i); + _loop_31(i); } proj.rootFiles = filesToKeep; return excludedFiles; }; ProjectService.prototype.openExternalProject = function (proj) { + // typingOptions has been deprecated and is only supported for backward compatibility + // purposes. It should be removed in future releases - use typeAcquisition instead. if (proj.typingOptions && !proj.typeAcquisition) { var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); proj.typeAcquisition = typeAcquisition; @@ -115426,6 +119528,7 @@ var ts; rootFiles.push(file); } } + // sort config files to simplify comparison later if (tsConfigFiles) { tsConfigFiles.sort(); } @@ -115442,16 +119545,22 @@ var ts; else { externalProject.enableLanguageService(); } + // external project already exists and not config files were added - update the project and return; this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); return; } + // some config files were added to external project (that previously were not there) + // close existing project and later we'll open a set of configured projects for these files this.closeExternalProject(proj.projectFileName); } else if (this.externalProjectToConfiguredProjectMap.get(proj.projectFileName)) { + // this project used to include config files if (!tsConfigFiles) { + // config files were removed from the project - close existing external project which in turn will close configured projects this.closeExternalProject(proj.projectFileName); } else { + // project previously had some config files - compare them with new set of files and close all configured projects that correspond to unused files var oldConfigFiles = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName); var iNew = 0; var iOld = 0; @@ -115466,47 +119575,59 @@ var ts; iNew++; } else { + // record existing config files so avoid extra add-refs (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); iOld++; iNew++; } } for (var i = iOld; i < oldConfigFiles.length; i++) { + // projects for all remaining old config files should be closed this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]); } } } if (tsConfigFiles) { + // store the list of tsconfig files that belong to the external project this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, tsConfigFiles); for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { + // errors are stored in the project project = this.createConfiguredProject(tsconfigFile); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { + // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project project.addExternalProjectReference(); } } } else { + // no config files - remove the item from the collection this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); } }; ProjectService.prototype.hasDeferredExtension = function () { - for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { + for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { // TODO: GH#18217 var extension = _a[_i]; - if (extension.scriptKind === 7) { + if (extension.scriptKind === 7 /* Deferred */) { return true; } } return false; }; + /** Makes a filename safe to insert in a RegExp */ ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; return ProjectService; }()); server.ProjectService = ProjectService; + /* @internal */ + function isConfigFile(config) { + return config.kind !== undefined; + } + server.isConfigFile = isConfigFile; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -115524,6 +119645,18 @@ var ts; return ((1e9 * seconds) + nanoseconds) / 1000000.0; } function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) { + // Checking for semantic diagnostics is an expensive process. We want to avoid it if we + // know for sure it is not needed. + // For instance, .d.ts files injected by ATA automatically do not produce any relevant + // errors to a JS- only project. + // + // Note that configured projects can set skipLibCheck (on by default in jsconfig.json) to + // disable checking for declaration files. We only need to verify for inferred projects (e.g. + // miscellaneous context in VS) and external projects(e.g.VS.csproj project) with only JS + // files. + // + // We still want to check .js files in a JS-only inferred or external project (e.g. if the + // file has '// @ts-check'). if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && project.isJsOnlyProject()) { var scriptInfo = project.getScriptInfoForNormalizedPath(file); @@ -115531,27 +119664,8 @@ var ts; } return false; } - function compareNumber(a, b) { - return a - b; - } - function compareFileStart(a, b) { - if (a.file < b.file) { - return -1; - } - else if (a.file === b.file) { - var n = compareNumber(a.start.line, b.start.line); - if (n === 0) { - return compareNumber(a.start.offset, b.start.offset); - } - else - return n; - } - else { - return 1; - } - } function formatDiag(fileName, project, diag) { - var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); // TODO: GH#18217 return { start: scriptInfo.positionToLineOffset(diag.start), end: scriptInfo.positionToLineOffset(diag.start + diag.length), @@ -115559,31 +119673,55 @@ var ts; code: diag.code, category: ts.diagnosticCategoryName(diag), reportsUnnecessary: diag.reportsUnnecessary, - source: diag.source + source: diag.source, + relatedInformation: ts.map(diag.relatedInformation, formatRelatedInformation), + }; + } + function formatRelatedInformation(info) { + if (!info.file) { + return { + message: ts.flattenDiagnosticMessageText(info.messageText, "\n"), + category: ts.diagnosticCategoryName(info), + code: info.code + }; + } + return { + span: { + start: convertToLocation(ts.getLineAndCharacterOfPosition(info.file, info.start)), + end: convertToLocation(ts.getLineAndCharacterOfPosition(info.file, info.start + info.length)), + file: info.file.fileName + }, + message: ts.flattenDiagnosticMessageText(info.messageText, "\n"), + category: ts.diagnosticCategoryName(info), + code: info.code }; } function convertToLocation(lineAndCharacter) { return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; } function formatConfigFileDiag(diag, includeFileName) { - var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start))); - var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length))); + var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start))); // TODO: GH#18217 + var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length))); // TODO: GH#18217 var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n"); var code = diag.code, source = diag.source; var category = ts.diagnosticCategoryName(diag); - return includeFileName ? { start: start, end: end, text: text, code: code, category: category, source: source, reportsUnnecessary: diag.reportsUnnecessary, fileName: diag.file && diag.file.fileName } : - { start: start, end: end, text: text, code: code, category: category, reportsUnnecessary: diag.reportsUnnecessary, source: source }; + var common = { + start: start, + end: end, + text: text, + code: code, + category: category, + reportsUnnecessary: diag.reportsUnnecessary, + source: source, + relatedInformation: ts.map(diag.relatedInformation, formatRelatedInformation), + }; + return includeFileName + ? __assign({}, common, { fileName: diag.file && diag.file.fileName }) : common; } function allEditsBeforePos(edits, pos) { - for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var edit = edits_1[_i]; - if (ts.textSpanEnd(edit.span) >= pos) { - return false; - } - } - return true; + return edits.every(function (edit) { return ts.textSpanEnd(edit.span) < pos; }); } - server.CommandNames = server.protocol.CommandTypes; + server.CommandNames = server.protocol.CommandTypes; // tslint:disable-line variable-name function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); var json = JSON.stringify(msg); @@ -115594,7 +119732,11 @@ var ts; return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; } server.formatMessage = formatMessage; - var MultistepOperation = (function () { + /** + * Represents operation that can schedule its next step to be executed later. + * Scheduling is done via instance of NextStep. If on current step subsequent step was not scheduled - operation is assumed to be completed. + */ + var MultistepOperation = /** @class */ (function () { function MultistepOperation(operationHost) { this.operationHost = operationHost; } @@ -115641,6 +119783,7 @@ var ts; } catch (e) { stop = true; + // ignore cancellation request if (!(e instanceof ts.OperationCanceledException)) { this.operationHost.logError(e, "delayed processing of request " + this.requestId); } @@ -115666,6 +119809,7 @@ var ts; }; return MultistepOperation; }()); + /** @internal */ function toEvent(eventName, body) { return { seq: 0, @@ -115675,12 +119819,12 @@ var ts; }; } server.toEvent = toEvent; - function isProjectsArray(projects) { - return !!projects.length; - } + /** + * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. + */ function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { - var outputs = ts.flatMap(isProjectsArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); - if (!isProjectsArray(projects) && projects.symLinkedProjects) { + var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { var value = getValue(path); outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); @@ -115690,7 +119834,155 @@ var ts; ? ts.sortAndDeduplicate(outputs, comparer, areEqual) : ts.deduplicate(outputs, areEqual); } - var Session = (function () { + function combineProjectOutputFromEveryProject(projectService, action, areEqual) { + var outputs = []; + projectService.forEachEnabledProject(function (project) { + var theseOutputs = action(project); + outputs.push.apply(outputs, theseOutputs.filter(function (output) { return !outputs.some(function (o) { return areEqual(o, output); }); })); + }); + return outputs; + } + function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, projectService, action, getLocation, resultsEqual) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, + /*initialLocation*/ undefined, projectService, function (_a, tryAddToTodo) { + var project = _a.project; + for (var _i = 0, _b = action(project); _i < _b.length; _i++) { + var output = _b[_i]; + if (!ts.contains(outputs, output, resultsEqual) && !tryAddToTodo(project, getLocation(output))) { + outputs.push(output); + } + } + }, + /*getDefinition*/ undefined); + return outputs; + } + function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, projectService, findInStrings, findInComments) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + var project = _a.project, location = _a.location; + for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.position, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { + var output = _b[_i]; + if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { + outputs.push(output); + } + } + }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); + return outputs; + } + function getDefinitionLocation(defaultProject, initialLocation) { + var infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.position); + var info = infos && ts.firstOrUndefined(infos); + return info && { fileName: info.fileName, position: info.textSpan.start }; + } + function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { + var outputs = []; + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + var project = _a.project, location = _a.location; + var _loop_33 = function (outputReferencedSymbol) { + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + if (!symbolToAddTo) { + symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + outputs.push(symbolToAddTo); + } + for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + symbolToAddTo.references.push(ref); + } + } + }; + for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.position) || server.emptyArray; _i < _b.length; _i++) { + var outputReferencedSymbol = _b[_i]; + _loop_33(outputReferencedSymbol); + } + }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); + return outputs.filter(function (o) { return o.references.length !== 0; }); + } + function forEachProjectInProjects(projects, path, cb) { + for (var _i = 0, _a = ts.isArray(projects) ? projects : projects.projects; _i < _a.length; _i++) { + var project = _a[_i]; + cb(project, path); + } + if (!ts.isArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (symlinkedProjects, symlinkedPath) { + for (var _i = 0, symlinkedProjects_1 = symlinkedProjects; _i < symlinkedProjects_1.length; _i++) { + var project = symlinkedProjects_1[_i]; + cb(project, symlinkedPath); + } + }); + } + } + function combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, cb, getDefinition) { + var toDo; + var seenProjects = ts.createMap(); + forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { + // TLocation shoud be either `sourcemaps.SourceMappableLocation` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. + var location = (initialLocation ? { fileName: path, position: initialLocation.position } : undefined); + toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb); + }); + // After initial references are collected, go over every other project and see if it has a reference for the symbol definition. + if (getDefinition) { + var memGetDefinition_1 = ts.memoize(getDefinition); + projectService.forEachEnabledProject(function (project) { + if (!ts.addToSeen(seenProjects, project.projectName)) + return; + var definition = getDefinitionInProject(memGetDefinition_1(), defaultProject, project); + if (definition) { + toDo = callbackProjectAndLocation({ project: project, location: definition }, projectService, toDo, seenProjects, cb); + } + }); + } + while (toDo && toDo.length) { + toDo = callbackProjectAndLocation(ts.Debug.assertDefined(toDo.pop()), projectService, toDo, seenProjects, cb); + } + } + function getDefinitionInProject(definition, definingProject, project) { + if (!definition || project.containsFile(server.toNormalizedPath(definition.fileName))) + return definition; + var mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedLocation(definition); + return mappedDefinition && project.containsFile(server.toNormalizedPath(mappedDefinition.fileName)) ? mappedDefinition : undefined; + } + function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) { + if (projectAndLocation.project.getCancellationToken().isCancellationRequested()) + return undefined; // Skip rest of toDo if cancelled + cb(projectAndLocation, function (project, location) { + seenProjects.set(projectAndLocation.project.projectName, true); + var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); + if (!originalLocation) + return false; + var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); + toDo = toDo || []; + for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { + var project_1 = _a[_i]; + addToTodo({ project: project_1, location: originalLocation }, toDo, seenProjects); + } + var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); + if (symlinkedProjectsMap) { + symlinkedProjectsMap.forEach(function (symlinkedProjects) { + for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { + var symlinkedProject = symlinkedProjects_2[_i]; + addToTodo({ project: symlinkedProject, location: originalLocation }, toDo, seenProjects); + } + }); + } + return true; + }); + return toDo; + } + function addToTodo(projectAndLocation, toDo, seenProjects) { + if (ts.addToSeen(seenProjects, projectAndLocation.project.projectName)) + toDo.push(projectAndLocation); + } + function documentSpanLocation(_a) { + var fileName = _a.fileName, textSpan = _a.textSpan; + return { fileName: fileName, position: textSpan.start }; + } + function getMappedLocation(location, projectService, project) { + var mapsTo = project.getSourceMapper().tryGetOriginalLocation(location); + return mapsTo && projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined; + } + var Session = /** @class */ (function () { function Session(opts) { var _a; var _this = this; @@ -115702,15 +119994,18 @@ var ts; }, _a[server.CommandNames.OpenExternalProject] = function (request) { _this.projectService.openExternalProject(request.arguments); - return _this.requiredResponse(true); + // TODO: GH#20447 report errors + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.OpenExternalProjects] = function (request) { _this.projectService.openExternalProjects(request.arguments.projects); - return _this.requiredResponse(true); + // TODO: GH#20447 report errors + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.CloseExternalProject] = function (request) { _this.projectService.closeExternalProject(request.arguments.projectFileName); - return _this.requiredResponse(true); + // TODO: GH#20447 report errors + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.SynchronizeProjectList] = function (request) { var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); @@ -115725,71 +120020,76 @@ var ts; info: p.info, changes: p.changes, files: p.files, - projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, /*scriptInfo*/ undefined) }; }); return _this.requiredResponse(converted); }, _a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) { _this.changeSeq++; - _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); - return _this.requiredResponse(true); + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); // TODO: GH#18217 + // TODO: report errors + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.Exit] = function () { _this.exit(); return _this.notRequired(); }, _a[server.CommandNames.Definition] = function (request) { - return _this.requiredResponse(_this.getDefinition(request.arguments, true)); + return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.DefinitionFull] = function (request) { - return _this.requiredResponse(_this.getDefinition(request.arguments, false)); + return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.DefinitionAndBoundSpan] = function (request) { - return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, true)); + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.DefinitionAndBoundSpanFull] = function (request) { - return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, false)); + return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ false)); + }, + _a[server.CommandNames.EmitOutput] = function (request) { + return _this.requiredResponse(_this.getEmitOutput(request.arguments)); }, _a[server.CommandNames.TypeDefinition] = function (request) { return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, _a[server.CommandNames.Implementation] = function (request) { - return _this.requiredResponse(_this.getImplementation(request.arguments, true)); + return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.ImplementationFull] = function (request) { - return _this.requiredResponse(_this.getImplementation(request.arguments, false)); + return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.References] = function (request) { - return _this.requiredResponse(_this.getReferences(request.arguments, true)); + return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.ReferencesFull] = function (request) { - return _this.requiredResponse(_this.getReferences(request.arguments, false)); + return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.Rename] = function (request) { - return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); + return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.RenameLocationsFull] = function (request) { - return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); + return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.RenameInfoFull] = function (request) { return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[server.CommandNames.Open] = function (request) { - _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined); + _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), // TODO: GH#18217 + request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined); return _this.notRequired(); }, _a[server.CommandNames.Quickinfo] = function (request) { - return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.QuickinfoFull] = function (request) { - return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.GetOutliningSpans] = function (request) { - return _this.requiredResponse(_this.getOutliningSpans(request.arguments, true)); + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.GetOutliningSpansFull] = function (request) { - return _this.requiredResponse(_this.getOutliningSpans(request.arguments, false)); + return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.TodoComments] = function (request) { return _this.requiredResponse(_this.getTodoComments(request.arguments)); @@ -115827,17 +120127,20 @@ var ts; _a[server.CommandNames.FormatRangeFull] = function (request) { return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, + _a[server.CommandNames.CompletionInfo] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionInfo)); + }, _a[server.CommandNames.Completions] = function (request) { - return _this.requiredResponse(_this.getCompletions(request.arguments, true)); + return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.Completions)); }, _a[server.CommandNames.CompletionsFull] = function (request) { - return _this.requiredResponse(_this.getCompletions(request.arguments, false)); + return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionsFull)); }, _a[server.CommandNames.CompletionDetails] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, true)); + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.CompletionDetailsFull] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, false)); + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) { return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); @@ -115846,10 +120149,10 @@ var ts; return _this.requiredResponse(_this.emitFile(request.arguments)); }, _a[server.CommandNames.SignatureHelp] = function (request) { - return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.SignatureHelpFull] = function (request) { - return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); @@ -115859,7 +120162,7 @@ var ts; }, _a[server.CommandNames.Cleanup] = function () { _this.cleanup(); - return _this.requiredResponse(true); + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -115884,7 +120187,7 @@ var ts; }, _a[server.CommandNames.Configure] = function (request) { _this.projectService.setHostConfiguration(request.arguments); - _this.doOutput(undefined, server.CommandNames.Configure, request.seq, true); + _this.doOutput(/*info*/ undefined, server.CommandNames.Configure, request.seq, /*success*/ true); return _this.notRequired(); }, _a[server.CommandNames.Reload] = function (request) { @@ -115902,41 +120205,41 @@ var ts; return _this.notRequired(); }, _a[server.CommandNames.Navto] = function (request) { - return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.NavtoFull] = function (request) { - return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.Brace] = function (request) { - return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); + return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.BraceFull] = function (request) { - return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); + return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.NavBar] = function (request) { - return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.NavBarFull] = function (request) { - return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.NavTree] = function (request) { - return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.NavTreeFull] = function (request) { - return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); + return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.Occurrences] = function (request) { return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, _a[server.CommandNames.DocumentHighlights] = function (request) { - return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.DocumentHighlightsFull] = function (request) { - return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.CompilerOptionsForInferredProjects] = function (request) { _this.setCompilerOptionsForInferredProjects(request.arguments); - return _this.requiredResponse(true); + return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.ProjectInfo] = function (request) { return _this.requiredResponse(_this.getProjectInfo(request.arguments)); @@ -115949,16 +120252,16 @@ var ts; return _this.requiredResponse(_this.getJsxClosingTag(request.arguments)); }, _a[server.CommandNames.GetCodeFixes] = function (request) { - return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); + return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.GetCodeFixesFull] = function (request) { - return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); + return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.GetCombinedCodeFix] = function (request) { - return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, true)); + return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.GetCombinedCodeFixFull] = function (request) { - return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, false)); + return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.ApplyCodeActionCommand] = function (request) { return _this.requiredResponse(_this.applyCodeActionCommand(request.arguments)); @@ -115970,22 +120273,22 @@ var ts; return _this.requiredResponse(_this.getApplicableRefactors(request.arguments)); }, _a[server.CommandNames.GetEditsForRefactor] = function (request) { - return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, true)); + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.GetEditsForRefactorFull] = function (request) { - return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, false)); + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.OrganizeImports] = function (request) { - return _this.requiredResponse(_this.organizeImports(request.arguments, true)); + return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.OrganizeImportsFull] = function (request) { - return _this.requiredResponse(_this.organizeImports(request.arguments, false)); + return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ false)); }, _a[server.CommandNames.GetEditsForFileRename] = function (request) { - return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, true)); + return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ true)); }, _a[server.CommandNames.GetEditsForFileRenameFull] = function (request) { - return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, false)); + return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ false)); }, _a)); this.host = opts.host; @@ -116026,7 +120329,7 @@ var ts; syntaxOnly: opts.syntaxOnly, }; this.projectService = new server.ProjectService(settings); - this.gcTimer = new server.GcTimer(this.host, 7000, this.logger); + this.gcTimer = new server.GcTimer(this.host, /*delay*/ 7000, this.logger); } Session.prototype.sendRequestCompletedEvent = function (requestId) { this.event({ request_seq: requestId }, "requestCompleted"); @@ -116037,9 +120340,13 @@ var ts; var openFiles = event.data.openFiles; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case server.LargeFileReferencedEvent: + var _a = event.data, file = _a.file, fileSize = _a.fileSize, maxFileSize_1 = _a.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, "largeFileReferenced"); + break; case server.ConfigFileDiagEvent: - var _a = event.data, triggerFile = _a.triggerFile, configFile = _a.configFileName, diagnostics = _a.diagnostics; - var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); + var _b = event.data, triggerFile = _b.triggerFile, configFile = _b.configFileName, diagnostics = _b.diagnostics; + var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ true); }); this.event({ triggerFile: triggerFile, configFile: configFile, @@ -116070,8 +120377,10 @@ var ts; if (openFiles.length) { if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { var checkList_1 = this.createCheckList(openFiles); - this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, true); }); + // For now only queue error checking for open files. We can change this to include non open files as well + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, /*requireOpen*/ true); }); } + // Send project changed event this.event({ openFiles: openFiles }, "projectsUpdatedInBackground"); @@ -116099,8 +120408,10 @@ var ts; Session.prototype.event = function (body, eventName) { this.send(toEvent(eventName, body)); }; + // For backwards-compatibility only. + /** @deprecated */ Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { - this.doOutput(info, cmdName, reqSeq, !errorMsg, errorMsg); + this.doOutput(info, cmdName, reqSeq, /*success*/ !errorMsg, errorMsg); // TODO: GH#18217 }; Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) { var res = { @@ -116141,10 +120452,11 @@ var ts; this.logError(err, kind); } }; + /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) { var _this = this; if (requireOpen === void 0) { requireOpen = true; } - ts.Debug.assert(!this.suppressDiagnosticEvents); + ts.Debug.assert(!this.suppressDiagnosticEvents); // Caller's responsibility var seq = this.changeSeq; var followMs = Math.min(ms, 200); var index = 0; @@ -116154,7 +120466,8 @@ var ts; } var _a = checkList[index], fileName = _a.fileName, project = _a.project; index++; - project.updateGraph(); + // Ensure the project is upto date before checking if this file is present in the project + server.updateProjectIfDirty(project); if (!project.containsFile(fileName, requireOpen)) { return; } @@ -116194,7 +120507,7 @@ var ts; this.logger.info("cleaning " + caption); for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { var p = projects_5[_i]; - p.getLanguageService(false).cleanupSemanticCache(); + p.getLanguageService(/*ensureSynchronized*/ false).cleanupSemanticCache(); } }; Session.prototype.cleanup = function () { @@ -116227,7 +120540,7 @@ var ts; var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return !!diagnostic.file && diagnostic.file.fileName === configFile; }); return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : - ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, false); }); + ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ false); }); }; Session.prototype.convertToDiagnosticsWithLinePositionFromDiagnosticFile = function (diagnostics) { var _this = this; @@ -116238,12 +120551,17 @@ var ts; category: ts.diagnosticCategoryName(d), code: d.code, startLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start))), - endLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length))) + endLocation: (d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length))), + relatedInformation: ts.map(d.relatedInformation, formatRelatedInformation) }); }); }; Session.prototype.getCompilerOptionsDiagnostics = function (args) { var project = this.getProject(args.projectFileName); - return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), undefined); + // Get diagnostics that dont have associated file with them + // The diagnostics which have file would be in config file and + // would be reported as part of configFileDiagnostics + return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), + /*scriptInfo*/ undefined); }; Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { var _this = this; @@ -116256,7 +120574,8 @@ var ts; source: d.source, startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length), - reportsUnnecessary: d.reportsUnnecessary + reportsUnnecessary: d.reportsUnnecessary, + relatedInformation: ts.map(d.relatedInformation, formatRelatedInformation), }); }); }; Session.prototype.getDiagnosticsWorker = function (args, isSemantic, selector, includeLinePosition) { @@ -116273,38 +120592,67 @@ var ts; Session.prototype.getDefinition = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); - if (!definitions) { - return server.emptyArray; - } - if (simplifiedResult) { - return this.mapDefinitionInfo(definitions, project); - } - return definitions.map(Session.mapToOriginalLocation); + var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || server.emptyArray, project); + return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(Session.mapToOriginalLocation); + }; + Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { + var _this = this; + return definitions.map(function (info) { + var newLoc = getMappedLocation(documentSpanLocation(info), _this.projectService, project); + return !newLoc ? info : { + containerKind: info.containerKind, + containerName: info.containerName, + fileName: newLoc.fileName, + kind: info.kind, + name: info.name, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan, + }; + }); }; Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - var scriptInfo = project.getScriptInfo(file); - var definitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); - if (!definitionAndBoundSpan || !definitionAndBoundSpan.definitions) { + var scriptInfo = ts.Debug.assertDefined(project.getScriptInfo(file)); + var unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); + if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) { return { definitions: server.emptyArray, - textSpan: undefined + textSpan: undefined // TODO: GH#18217 }; } + var definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project); + var textSpan = unmappedDefinitionAndBoundSpan.textSpan; if (simplifiedResult) { return { - definitions: this.mapDefinitionInfo(definitionAndBoundSpan.definitions, project), - textSpan: this.toLocationTextSpan(definitionAndBoundSpan.textSpan, scriptInfo) + definitions: this.mapDefinitionInfo(definitions, project), + textSpan: this.toLocationTextSpan(textSpan, scriptInfo) }; } - return __assign({}, definitionAndBoundSpan, { definitions: definitionAndBoundSpan.definitions.map(Session.mapToOriginalLocation) }); + return { + definitions: definitions.map(Session.mapToOriginalLocation), + textSpan: textSpan, + }; + }; + Session.prototype.getEmitOutput = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEmitOutput(file); }; Session.prototype.mapDefinitionInfo = function (definitions, project) { var _this = this; return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); }); }; + /* + * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in + * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols. + * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a + * set of additional fields, and does the reverse for VS (store the .d.ts location where + * it used to be and stores the .ts location in the additional fields). + */ Session.mapToOriginalLocation = function (def) { if (def.originalFileName) { ts.Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is"); @@ -116314,7 +120662,7 @@ var ts; }; Session.prototype.toFileSpan = function (fileName, textSpan, project) { var ls = project.getLanguageService(); - var start = ls.toLineColumnOffset(fileName, textSpan.start); + var start = ls.toLineColumnOffset(fileName, textSpan.start); // TODO: GH#18217 var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan)); return { file: fileName, @@ -116325,20 +120673,31 @@ var ts; Session.prototype.getTypeDefinition = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); - if (!definitions) { - return server.emptyArray; - } + var definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || server.emptyArray, project); return this.mapDefinitionInfo(definitions, project); }; + Session.prototype.mapImplementationLocations = function (implementations, project) { + var _this = this; + return implementations.map(function (info) { + var newLoc = getMappedLocation(documentSpanLocation(info), _this.projectService, project); + return !newLoc ? info : { + fileName: newLoc.fileName, + kind: info.kind, + displayParts: info.displayParts, + textSpan: { + start: newLoc.position, + length: info.textSpan.length + }, + originalFileName: info.fileName, + originalTextSpan: info.textSpan, + }; + }); + }; Session.prototype.getImplementation = function (args, simplifiedResult) { var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - var implementations = project.getLanguageService().getImplementationAtPosition(file, position); - if (!implementations) { - return server.emptyArray; - } + var implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || server.emptyArray, project); if (simplifiedResult) { return implementations.map(function (_a) { var fileName = _a.fileName, textSpan = _a.textSpan; @@ -116363,6 +120722,7 @@ var ts; file: fileName, isWriteAccess: isWriteAccess, }; + // no need to serialize the property if it is not true if (isInString) { result.isInString = isInString; } @@ -116372,23 +120732,26 @@ var ts; Session.prototype.getSyntacticDiagnosticsSync = function (args) { var configFile = this.getConfigFileAndProject(args).configFile; if (configFile) { + // all the config file errors are reported as part of semantic check so nothing to report here return server.emptyArray; } - return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition); + return this.getDiagnosticsWorker(args, /*isSemantic*/ false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project; if (configFile) { - return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); + return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); // TODO: GH#18217 } - return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, !!args.includeLinePosition); + return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, !!args.includeLinePosition); }; Session.prototype.getSuggestionDiagnosticsSync = function (args) { var configFile = this.getConfigFileAndProject(args).configFile; if (configFile) { + // Currently there are no info diagnostics for config files. return server.emptyArray; } - return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, !!args.includeLinePosition); + // isSemantic because we don't want to info diagnostics in declaration files for JS-only users + return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, !!args.includeLinePosition); }; Session.prototype.getJsxClosingTag = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; @@ -116428,15 +120791,15 @@ var ts; this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); }; Session.prototype.getProjectInfo = function (args) { - return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false); + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, /*excludeConfigFiles*/ false); }; Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName).project; - project.updateGraph(); + server.updateProjectIfDirty(project); var projectInfo = { configFileName: project.getProjectName(), languageServiceDisabled: !project.languageServiceEnabled, - fileNames: needFileNameList ? project.getFileNames(false, excludeConfigFiles) : undefined + fileNames: needFileNameList ? project.getFileNames(/*excludeFilesFromExternalLibraries*/ false, excludeConfigFiles) : undefined }; return projectInfo; }; @@ -116445,7 +120808,7 @@ var ts; var position = this.getPositionInFile(args, file); return project.getLanguageService().getRenameInfo(file, position); }; - Session.prototype.getProjects = function (args) { + Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { var projects; var symLinkedProjects; if (args.projectFileName) { @@ -116455,15 +120818,21 @@ var ts; } } else { - var scriptInfo = this.projectService.getScriptInfo(args.file); + var scriptInfo = getScriptInfoEnsuringProjectsUptoDate ? + this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : + this.projectService.getScriptInfo(args.file); + if (!scriptInfo) { + return ignoreNoProjectError ? server.emptyArray : server.Errors.ThrowNoProject(); + } projects = scriptInfo.containingProjects; symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } + // filter handles case when 'projects' is undefined projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); }); - if ((!projects || !projects.length) && !symLinkedProjects) { + if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { return server.Errors.ThrowNoProject(); } - return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; + return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; // TODO: GH#18217 }; Session.prototype.getDefaultProject = function (args) { if (args.projectFileName) { @@ -116476,142 +120845,69 @@ var ts; return info.getDefaultProject(); }; Session.prototype.getRenameLocations = function (args, simplifiedResult) { - var _this = this; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); - if (simplifiedResult) { - var defaultProject = this.getDefaultProject(args); - var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); - if (!renameInfo) { - return undefined; - } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: server.emptyArray - }; - } - var fileSpans = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { - var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); - if (!renameLocations) { - return server.emptyArray; - } - return renameLocations.map(function (location) { - var locationScriptInfo = project.getScriptInfo(location.fileName); - return { - file: location.fileName, - start: locationScriptInfo.positionToLineOffset(location.textSpan.start), - end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)), - }; - }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = []; - for (var _i = 0, fileSpans_1 = fileSpans; _i < fileSpans_1.length; _i++) { - var cur = fileSpans_1[_i]; - var curFileAccum = void 0; - if (locs.length > 0) { - curFileAccum = locs[locs.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; - } - } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - locs.push(curFileAccum); - } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - } - return { info: renameInfo, locs: locs }; - } - else { - return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (p, file) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); - } - function renameLocationIsEqualTo(a, b) { - if (a === b) { - return true; - } - if (!a || !b) { - return false; - } - return a.fileName === b.fileName && - a.textSpan.start === b.textSpan.start && - a.textSpan.length === b.textSpan.length; - } - function compareRenameLocation(a, b) { - if (a.file < b.file) { - return -1; - } - else if (a.file > b.file) { - return 1; - } - else { - if (a.start.line < b.start.line) { - return 1; - } - else if (a.start.line > b.start.line) { - return -1; - } - else { - return b.start.offset - a.start.offset; - } - } + var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, position: position }, this.projectService, !!args.findInStrings, !!args.findInComments); + if (!simplifiedResult) + return locations; + var defaultProject = this.getDefaultProject(args); + var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + return { info: renameInfo, locs: this.toSpanGroups(locations) }; + }; + // strips 'triggerSpan' + Session.mapRenameInfo = function (_a) { + var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; + return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + }; + Session.prototype.toSpanGroups = function (locations) { + var map = ts.createMap(); + for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { + var _a = locations_1[_i], fileName = _a.fileName, textSpan = _a.textSpan; + var group_2 = map.get(fileName); + if (!group_2) + map.set(fileName, group_2 = { file: fileName, locs: [] }); + group_2.locs.push(this.toLocationTextSpan(textSpan, ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); } + return ts.arrayFrom(map.values()); }; Session.prototype.getReferences = function (args, simplifiedResult) { var _this = this; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); - var defaultProject = this.getDefaultProject(args); - var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - var position = this.getPosition(args, scriptInfo); + var position = this.getPositionInFile(args, file); + var references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, position: position }, this.projectService); if (simplifiedResult) { + var defaultProject = this.getDefaultProject(args); + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); - var displayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : ""; + var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : ""; var nameSpan = nameInfo && nameInfo.textSpan; - var nameColStart = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; - var nameText = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; - var refs = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { - var references = project.getLanguageService().getReferencesAtPosition(file, position); - if (!references) { - return server.emptyArray; - } - return references.map(function (ref) { - var refScriptInfo = project.getScriptInfo(ref.fileName); - var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); - var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); - var lineText = refScriptInfo.getSnapshot().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; + var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; + var symbolName_4 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; + var refs = ts.flatMap(references, function (referencedSymbol) { + return referencedSymbol.references.map(function (_a) { + var fileName = _a.fileName, textSpan = _a.textSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition; + var scriptInfo = ts.Debug.assertDefined(_this.projectService.getScriptInfo(fileName)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var lineSpan = scriptInfo.lineToTextSpan(start.line - 1); + var lineText = scriptInfo.getSnapshot().getText(lineSpan.start, ts.textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); + return __assign({}, toFileSpan(fileName, textSpan, scriptInfo), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition }); }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; + }); + var result = { refs: refs, symbolName: symbolName_4, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; + return result; } else { - return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { return project.getLanguageService().findReferences(file, position); }, undefined, ts.equateValues); - } - function areReferencesResponseItemsForTheSameLocation(a, b) { - if (a && b) { - return a.file === b.file && - a.start === b.start && - a.end === b.end; - } - return false; + return references; } }; + /** + * @param fileName is the name of the file to be opened + * @param fileContent is a version of the file content that is known to be more up to date than the one on disk + */ Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { - this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, false, projectRootPath); + this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath); }; Session.prototype.getPosition = function (args, scriptInfo) { return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); @@ -116624,19 +120920,21 @@ var ts; return this.getFileAndProjectWorker(args.file, args.projectFileName); }; Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) { + // Since this is syntactic operation, there should always be project for the file + // we wouldnt have to ensure project but rather throw if we dont get project var file = server.toNormalizedPath(args.file); - var project = this.getProject(args.projectFileName) || this.projectService.getDefaultProjectForFile(file, false); + var project = this.getProject(args.projectFileName) || this.projectService.tryGetDefaultProjectForFile(file); if (!project) { return server.Errors.ThrowNoProject(); } return { file: file, - languageService: project.getLanguageService(false) + languageService: project.getLanguageService(/*ensureSynchronized*/ false) }; }; Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) { var file = server.toNormalizedPath(uncheckedFileName); - var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, true); + var project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file); return { file: file, project: project }; }; Session.prototype.getOutliningSpans = function (args, simplifiedResult) { @@ -116724,6 +121022,7 @@ var ts; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + // TODO: avoid duplicate code (with formatonkey) var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file)); if (!edits) { return undefined; @@ -116733,7 +121032,7 @@ var ts; Session.prototype.getFormattingEditsForRangeFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); - return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); + return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); // TODO: GH#18217 }; Session.prototype.getFormattingEditsForDocumentFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -116743,7 +121042,7 @@ var ts; Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file); - return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); // TODO: GH#18217 }; Session.prototype.getFormattingEditsAfterKeystroke = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -116751,6 +121050,12 @@ var ts; var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); var formatOptions = this.getFormatOptions(file); var edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + // Check whether we should auto-indent. This will be when + // the position is on a line containing only whitespace. + // This should leave the edits returned from + // getFormattingEditsAfterKeystroke either empty or pertaining + // only to the previous line. If all this is true, then + // add edits necessary to properly indent the current line. if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { var _b = scriptInfo.getLineInfo(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; if (lineText && lineText.search("\\S") < 0) { @@ -116762,12 +121067,13 @@ var ts; hasIndent++; } else if (lineText.charAt(i) === "\t") { - hasIndent += formatOptions.tabSize; + hasIndent += formatOptions.tabSize; // TODO: GH#18217 } else { break; } } + // i points to the first non whitespace character if (preferredIndent !== hasIndent) { var firstNoWhiteSpacePosition = absolutePosition + i; edits.push({ @@ -116788,25 +121094,29 @@ var ts; }; }); }; - Session.prototype.getCompletions = function (args, simplifiedResult) { + Session.prototype.getCompletions = function (args, kind) { var _this = this; - var prefix = args.prefix || ""; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); - if (simplifiedResult) { - return ts.mapDefined(completions && completions.entries, function (entry) { - if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; - var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; - return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; - } - }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); - } - else { + if (completions === undefined) + return undefined; + if (kind === "completions-full" /* CompletionsFull */) return completions; - } + var prefix = args.prefix || ""; + var entries = ts.mapDefined(completions.entries, function (entry) { + if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { + var name = entry.name, kind_2 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; + // Use `hasAction || undefined` to avoid serializing `false`. + return { name: name, kind: kind_2, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; + } + }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); + if (kind === "completions" /* Completions */) + return entries; + var res = __assign({}, completions, { entries: entries }); + return res; }; Session.prototype.getCompletionEntryDetails = function (args, simplifiedResult) { var _this = this; @@ -116819,18 +121129,17 @@ var ts; return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file)); }); return simplifiedResult - ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(project, action); }) })); }) + ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action); }) })); }) : result; }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { var _this = this; - var info = this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file); + var projects = this.getProjects(args, /*getScriptInfoEnsuringProjectsUptoDate*/ true, /*ignoreNoProjectError*/ true); + var info = this.projectService.getScriptInfo(args.file); if (!info) { return server.emptyArray; } - var projects = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; - var symLinkedProjects = !args.projectFileName && this.projectService.getSymlinkedProjects(info); - return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects, function (project, info) { + return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, projects, function (project, info) { var result; if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.isOrphan() && !project.getCompilationSettings().noEmit) { result = { @@ -116858,7 +121167,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); + var helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args); if (!helpItems) { return undefined; } @@ -116883,7 +121192,7 @@ var ts; var _this = this; return ts.mapDefined(fileNames, function (uncheckedFileName) { var fileName = server.toNormalizedPath(uncheckedFileName); - var project = defaultProject || _this.projectService.getDefaultProjectForFile(fileName, false); + var project = defaultProject || _this.projectService.tryGetDefaultProjectForFile(fileName); return project && { fileName: fileName, project: project }; }); }; @@ -116905,7 +121214,7 @@ var ts; this.changeSeq++; this.projectService.applyChangesToFile(scriptInfo, [{ span: { start: start, length: end - start }, - newText: args.insertString + newText: args.insertString // TODO: GH#18217 }]); } }; @@ -116915,8 +121224,9 @@ var ts; var info = this.projectService.getScriptInfoForNormalizedPath(file); if (info) { this.changeSeq++; + // make sure no changes happen before this one is finished if (info.reloadFromFile(tempFileName)) { - this.doOutput(undefined, server.CommandNames.Reload, reqSeq, true); + this.doOutput(/*info*/ undefined, server.CommandNames.Reload, reqSeq, /*success*/ true); } } }; @@ -116980,49 +121290,42 @@ var ts; : tree; }; Session.prototype.getNavigateToItems = function (args, simplifiedResult) { - var projects = this.getProjects(args); - var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; - if (simplifiedResult) { - return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { - if (fileName && !file) { - return undefined; - } - var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); - if (!navItems) { - return server.emptyArray; - } - return navItems.map(function (navItem) { - var scriptInfo = project.getScriptInfo(navItem.fileName); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - file: navItem.fileName, - start: scriptInfo.positionToLineOffset(navItem.textSpan.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)) - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.matchKind !== "none") { - bakedItem.matchKind = navItem.matchKind; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); + var _this = this; + var full = this.getFullNavigateToItems(args); + return !simplifiedResult ? full : full.map(function (navItem) { + var _a = _this.getFileAndProject({ file: navItem.fileName }), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfo(file); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + isCaseSensitive: navItem.isCaseSensitive, + matchKind: navItem.matchKind, + file: navItem.fileName, + start: scriptInfo.positionToLineOffset(navItem.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)) + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }; + Session.prototype.getFullNavigateToItems = function (args) { + var currentFileOnly = args.currentFileOnly, searchValue = args.searchValue, maxResultCount = args.maxResultCount; + if (currentFileOnly) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file); } else { - return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { - if (fileName && !file) { - return undefined; - } - return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); - }, undefined, navigateToItemIsEqualTo); + return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), this.projectService, function (project) { + return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()); + }, documentSpanLocation, navigateToItemIsEqualTo); } function navigateToItemIsEqualTo(a, b) { if (a === b) { @@ -117042,14 +121345,6 @@ var ts; a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length; } - function areNavToItemsForTheSameLocation(a, b) { - if (a && b) { - return a.file === b.file && - a.start === b.start && - a.end === b.end; - } - return false; - } }; Session.prototype.getSupportedCodeFixes = function () { return ts.getSupportedCodeFixes(); @@ -117067,7 +121362,7 @@ var ts; var _a = this.getStartAndEndPosition(args, scriptInfo), startPosition = _a.startPosition, endPosition = _a.endPosition; textRange = { pos: startPosition, end: endPosition }; } - return { position: position, textRange: textRange }; + return { position: position, textRange: textRange }; // TODO: GH#18217 function getPosition(loc) { return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); } @@ -117095,7 +121390,7 @@ var ts; var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); mappedRenameLocation = getLocationInNewDocument(ts.getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); } - return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(project, edits) }; + return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(edits) }; } else { return result; @@ -117107,27 +121402,28 @@ var ts; var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { - return this.mapTextChangesToCodeEdits(project, changes); + return this.mapTextChangesToCodeEdits(changes); } else { return changes; } }; Session.prototype.getEditsForFileRename = function (args, simplifiedResult) { - var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var changes = project.getLanguageService().getEditsForFileRename(server.toNormalizedPath(args.oldFilePath), server.toNormalizedPath(args.newFilePath), this.getFormatOptions(file), this.getPreferences(file)); - return simplifiedResult ? this.mapTextChangesToCodeEdits(project, changes) : changes; + var _this = this; + var oldPath = server.toNormalizedPath(args.oldFilePath); + var newPath = server.toNormalizedPath(args.newFilePath); + var formatOptions = this.getHostFormatOptions(); + var preferences = this.getHostPreferences(); + var changes = combineProjectOutputFromEveryProject(this.projectService, function (project) { return project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); }, function (a, b) { return a.fileName === b.fileName; }); + return simplifiedResult ? changes.map(function (c) { return _this.mapTextChangeToCodeEdit(c); }) : changes; }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { var _this = this; - if (args.errorCodes.length === 0) { - return undefined; - } var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); - return simplifiedResult ? codeActions.map(function (codeAction) { return _this.mapCodeFixAction(project, codeAction); }) : codeActions; + return simplifiedResult ? codeActions.map(function (codeAction) { return _this.mapCodeFixAction(codeAction); }) : codeActions; }; Session.prototype.getCombinedCodeFix = function (_a, simplifiedResult) { var scope = _a.scope, fixId = _a.fixId; @@ -117135,14 +121431,14 @@ var ts; var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { - return { changes: this.mapTextChangesToCodeEdits(project, res.changes), commands: res.commands }; + return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands }; } else { return res; } }; Session.prototype.applyCodeActionCommand = function (args) { - var commands = args.command; + var commands = args.command; // They should be sending back the command we sent them. for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; var project = this.getFileAndProject(command).project; @@ -117157,6 +121453,7 @@ var ts; } else { startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + // save the result so we don't always recompute args.startPosition = startPosition; } if (args.endPosition !== undefined) { @@ -117168,20 +121465,20 @@ var ts; } return { startPosition: startPosition, endPosition: endPosition }; }; - Session.prototype.mapCodeAction = function (project, _a) { + Session.prototype.mapCodeAction = function (_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; - return { description: description, changes: this.mapTextChangesToCodeEdits(project, changes), commands: commands }; + return { description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands }; }; - Session.prototype.mapCodeFixAction = function (project, _a) { + Session.prototype.mapCodeFixAction = function (_a) { var fixName = _a.fixName, description = _a.description, changes = _a.changes, commands = _a.commands, fixId = _a.fixId, fixAllDescription = _a.fixAllDescription; - return { fixName: fixName, description: description, changes: this.mapTextChangesToCodeEdits(project, changes), commands: commands, fixId: fixId, fixAllDescription: fixAllDescription }; + return { fixName: fixName, description: description, changes: this.mapTextChangesToCodeEdits(changes), commands: commands, fixId: fixId, fixAllDescription: fixAllDescription }; }; - Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { + Session.prototype.mapTextChangesToCodeEdits = function (textChanges) { var _this = this; - return textChanges.map(function (change) { - var path = server.normalizedPathToPath(server.toNormalizedPath(change.fileName), _this.host.getCurrentDirectory(), function (fileName) { return _this.getCanonicalFileName(fileName); }); - return mapTextChangesToCodeEdits(change, project.getSourceFileOrConfigFile(path)); - }); + return textChanges.map(function (change) { return _this.mapTextChangeToCodeEdit(change); }); + }; + Session.prototype.mapTextChangeToCodeEdit = function (change) { + return mapTextChangesToCodeEdits(change, this.projectService.getScriptInfoOrConfig(change.fileName)); }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { @@ -117206,29 +121503,31 @@ var ts; if (this.suppressDiagnosticEvents) { return; } - var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, /*projectFileName*/ undefined, /*needFileNameList*/ true, /*excludeConfigFiles*/ true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } - var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); + // No need to analyze lib.d.ts + var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); // TODO: GH#18217 if (fileNamesInProject.length === 0) { return; } + // Sort the file name list to make the recently touched files come first var highPriorityFiles = []; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; var normalizedFileName = server.toNormalizedPath(fileName); - var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); + var project = this.projectService.ensureDefaultProjectForFile(normalizedFileName); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) { highPriorityFiles.push(fileNameInProject); } else { - var info = this.projectService.getScriptInfo(fileNameInProject); + var info = this.projectService.getScriptInfo(fileNameInProject); // TODO: GH#18217 if (!info.isScriptOpen()) { - if (ts.fileExtensionIs(fileNameInProject, ".d.ts")) { + if (ts.fileExtensionIs(fileNameInProject, ".d.ts" /* Dts */)) { veryLowPriorityFiles.push(fileNameInProject); } else { @@ -117242,7 +121541,9 @@ var ts; } var sortedFiles = highPriorityFiles.concat(mediumPriorityFiles, lowPriorityFiles, veryLowPriorityFiles); var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); }); - this.updateErrorCheck(next, checkList, delay, false); + // Project level error analysis runs on background files too, therefore + // doesn't require the file to be opened + this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ false); }; Session.prototype.getCanonicalFileName = function (fileName) { var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); @@ -117268,7 +121569,7 @@ var ts; }; Session.prototype.resetCurrentRequest = function (requestId) { ts.Debug.assert(this.currentRequestId === requestId); - this.currentRequestId = undefined; + this.currentRequestId = undefined; // TODO: GH#18217 this.cancellationToken.resetRequest(requestId); }; Session.prototype.executeWithRequestId = function (requestId, f) { @@ -117287,7 +121588,7 @@ var ts; } else { this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err); - this.doOutput(undefined, server.CommandNames.Unknown, request.seq, false, "Unrecognized JSON command: " + request.command); + this.doOutput(/*info*/ undefined, server.CommandNames.Unknown, request.seq, /*success*/ false, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; @@ -117314,19 +121615,22 @@ var ts; } } if (response) { - this.doOutput(response, request.command, request.seq, true); + this.doOutput(response, request.command, request.seq, /*success*/ true); } else if (responseRequired) { - this.doOutput(undefined, request.command, request.seq, false, "No content available."); + this.doOutput(/*info*/ undefined, request.command, request.seq, /*success*/ false, "No content available."); } } catch (err) { if (err instanceof ts.OperationCanceledException) { - this.doOutput({ canceled: true }, request.command, request.seq, true); + // Handle cancellation exceptions + this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } this.logError(err, message); - this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack); + this.doOutput( + /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, + /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); } }; Session.prototype.getFormatOptions = function (file) { @@ -117335,27 +121639,32 @@ var ts; Session.prototype.getPreferences = function (file) { return this.projectService.getPreferences(file); }; + Session.prototype.getHostFormatOptions = function () { + return this.projectService.getHostFormatCodeOptions(); + }; + Session.prototype.getHostPreferences = function () { + return this.projectService.getHostPreferences(); + }; return Session; }()); server.Session = Session; - function mapTextChangesToCodeEdits(textChanges, sourceFile) { - ts.Debug.assert(!!textChanges.isNewFile === !sourceFile); - if (sourceFile) { - return { - fileName: textChanges.fileName, - textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, sourceFile); }), - }; - } - else { - return convertNewFileTextChangeToCodeEdit(textChanges); - } + function toFileSpan(fileName, textSpan, scriptInfo) { + return { file: fileName, start: scriptInfo.positionToLineOffset(textSpan.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)) }; } - function convertTextChangeToCodeEdit(change, sourceFile) { - return { - start: convertToLocation(sourceFile.getLineAndCharacterOfPosition(change.span.start)), - end: convertToLocation(sourceFile.getLineAndCharacterOfPosition(change.span.start + change.span.length)), - newText: change.newText ? change.newText : "", - }; + function mapTextChangesToCodeEdits(textChanges, scriptInfo) { + ts.Debug.assert(!!textChanges.isNewFile === !scriptInfo, "Expected isNewFile for (only) new files", function () { return JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo }); }); + return scriptInfo + ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, scriptInfo); }) } + : convertNewFileTextChangeToCodeEdit(textChanges); + } + function convertTextChangeToCodeEdit(change, scriptInfo) { + return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, ts.textSpanEnd(change.span)), newText: change.newText }; + } + function positionToLineOffset(info, position) { + return server.isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position); + } + function locationFromLineAndCharacter(lc) { + return { line: lc.line + 1, offset: lc.character + 1 }; } function convertNewFileTextChangeToCodeEdit(textChanges) { ts.Debug.assert(textChanges.textChanges.length === 1); @@ -117363,6 +121672,7 @@ var ts; ts.Debug.assert(change.span.start === 0 && change.span.length === 0); return { fileName: textChanges.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] }; } + /* @internal */ // Exported only for tests function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { var newText = applyEdits(oldText, renameFilename, edits); var _a = ts.computeLineAndCharacterOfPosition(ts.computeLineStarts(newText), renameLocation), line = _a.line, character = _a.character; @@ -117371,19 +121681,20 @@ var ts; server.getLocationInNewDocument = getLocationInNewDocument; function applyEdits(text, textFilename, edits) { for (var _i = 0, edits_2 = edits; _i < edits_2.length; _i++) { - var _a = edits_2[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + var _a = edits_2[_i], fileName = _a.fileName, textChanges_4 = _a.textChanges; if (fileName !== textFilename) { continue; } - for (var i = textChanges_1.length - 1; i >= 0; i--) { - var _b = textChanges_1[i], newText = _b.newText, _c = _b.span, start = _c.start, length_1 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_1); + for (var i = textChanges_4.length - 1; i >= 0; i--) { + var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_7 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_7); } } return text; } })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/*@internal*/ var ts; (function (ts) { var server; @@ -117398,12 +121709,12 @@ var ts; CharRangeSection[CharRangeSection["End"] = 4] = "End"; CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; })(CharRangeSection || (CharRangeSection = {})); - var EditWalker = (function () { + var EditWalker = /** @class */ (function () { function EditWalker() { this.goSubtree = true; this.lineIndex = new LineIndex(); this.endBranch = []; - this.state = 2; + this.state = 2 /* Entire */; this.initialText = ""; this.trailingText = ""; this.lineIndex.root = new LineNode(); @@ -117449,6 +121760,7 @@ var ts; if (lastZeroCount) { branchParent.remove(lastZeroCount); } + // path at least length two (root and leaf) var leafNode = this.startPath[this.startPath.length - 1]; if (lines.length > 0) { leafNode.text = lines[0]; @@ -117483,6 +121795,7 @@ var ts; } else { var insertionNode = this.startPath[this.startPath.length - 2]; + // no content for leaf node, so delete it insertionNode.remove(leafNode); for (var j = this.startPath.length - 2; j >= 0; j--) { this.startPath[j].updateCounts(); @@ -117491,15 +121804,20 @@ var ts; return this.lineIndex; }; EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) { + // have visited the path for start of range, now looking for end + // if range is on single line, we will never make this state transition if (lineCollection === this.lineCollectionAtBranch) { - this.state = 4; + this.state = 4 /* End */; } + // always pop stack because post only called when child has been visited this.stack.pop(); }; EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { + // currentNode corresponds to parent, but in the new tree var currentNode = this.stack[this.stack.length - 1]; - if ((this.state === 2) && (nodeType === 1)) { - this.state = 1; + if ((this.state === 2 /* Entire */) && (nodeType === 1 /* Start */)) { + // if range is on single line, we will never make this state transition + this.state = 1 /* Start */; this.branchNode = currentNode; this.lineCollectionAtBranch = lineCollection; } @@ -117512,14 +121830,14 @@ var ts; return new LineNode(); } switch (nodeType) { - case 0: + case 0 /* PreStart */: this.goSubtree = false; - if (this.state !== 4) { + if (this.state !== 4 /* End */) { currentNode.add(lineCollection); } break; - case 1: - if (this.state === 4) { + case 1 /* Start */: + if (this.state === 4 /* End */) { this.goSubtree = false; } else { @@ -117528,8 +121846,8 @@ var ts; this.startPath.push(child); } break; - case 2: - if (this.state !== 4) { + case 2 /* Entire */: + if (this.state !== 4 /* End */) { child = fresh(lineCollection); currentNode.add(child); this.startPath.push(child); @@ -117542,11 +121860,11 @@ var ts; } } break; - case 3: + case 3 /* Mid */: this.goSubtree = false; break; - case 4: - if (this.state !== 4) { + case 4 /* End */: + if (this.state !== 4 /* End */) { this.goSubtree = false; } else { @@ -117557,9 +121875,9 @@ var ts; } } break; - case 5: + case 5 /* PostEnd */: this.goSubtree = false; - if (this.state !== 1) { + if (this.state !== 1 /* Start */) { currentNode.add(lineCollection); } break; @@ -117568,21 +121886,24 @@ var ts; this.stack.push(child); } }; + // just gather text from the leaves EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) { - if (this.state === 1) { + if (this.state === 1 /* Start */) { this.initialText = ll.text.substring(0, relativeStart); } - else if (this.state === 2) { + else if (this.state === 2 /* Entire */) { this.initialText = ll.text.substring(0, relativeStart); this.trailingText = ll.text.substring(relativeStart + relativeLength); } else { + // state is CharRangeSection.End this.trailingText = ll.text.substring(relativeStart + relativeLength); } }; return EditWalker; }()); - var TextChange = (function () { + // text change information + var TextChange = /** @class */ (function () { function TextChange(pos, deleteLen, insertedText) { this.pos = pos; this.deleteLen = deleteLen; @@ -117593,11 +121914,11 @@ var ts; }; return TextChange; }()); - var ScriptVersionCache = (function () { + var ScriptVersionCache = /** @class */ (function () { function ScriptVersionCache() { this.changes = []; this.versions = new Array(ScriptVersionCache.maxVersions); - this.minVersion = 0; + this.minVersion = 0; // no versions earlier than min version will maintain change history this.currentVersion = 0; } ScriptVersionCache.prototype.versionToIndex = function (version) { @@ -117609,6 +121930,7 @@ var ts; ScriptVersionCache.prototype.currentVersionToIndex = function () { return this.currentVersion % ScriptVersionCache.maxVersions; }; + // REVIEW: can optimize by coalescing simple edits ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes.push(new TextChange(pos, deleteLen, insertedText)); if (this.changes.length > ScriptVersionCache.changeNumberThreshold || @@ -117659,7 +121981,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[this.versionToIndex(i)]; + var snap = this.versions[this.versionToIndex(i)]; // TODO: GH#18217 for (var _i = 0, _a = snap.changesSincePreviousVersion; _i < _a.length; _i++) { var textChange = _a[_i]; textChangeRanges.push(textChange.getTextChangeRange()); @@ -117689,7 +122011,7 @@ var ts; return ScriptVersionCache; }()); server.ScriptVersionCache = ScriptVersionCache; - var LineIndexSnapshot = (function () { + var LineIndexSnapshot = /** @class */ (function () { function LineIndexSnapshot(version, cache, index, changesSincePreviousVersion) { if (changesSincePreviousVersion === void 0) { changesSincePreviousVersion = server.emptyArray; } this.version = version; @@ -117715,8 +122037,10 @@ var ts; }; return LineIndexSnapshot; }()); - var LineIndex = (function () { + /* @internal */ + var LineIndex = /** @class */ (function () { function LineIndex() { + // set this to true to check each edit for accuracy this.checkEdits = false; } LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) { @@ -117788,12 +122112,12 @@ var ts; }; LineIndex.prototype.edit = function (pos, deleteLength, newText) { if (this.root.charCount() === 0) { - ts.Debug.assert(deleteLength === 0); + ts.Debug.assert(deleteLength === 0); // Can't delete from empty document if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; } - return undefined; + return undefined; // TODO: GH#18217 } else { var checkText = void 0; @@ -117804,6 +122128,7 @@ var ts; var walker = new EditWalker(); var suppressTrailingText = false; if (pos >= this.root.charCount()) { + // insert at end pos = this.root.charCount() - 1; var endString = this.getText(pos, 1); if (newText) { @@ -117816,10 +122141,13 @@ var ts; suppressTrailingText = true; } else if (deleteLength > 0) { + // check whether last characters deleted are line break var e = pos + deleteLength; var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText; if (zeroBasedColumn === 0) { - deleteLength += lineText.length; + // move range end just past line that will merge with previous line + deleteLength += lineText.length; // TODO: GH#18217 + // store text by appending to end of insertedText newText = newText ? newText + lineText : lineText; } } @@ -117867,7 +122195,7 @@ var ts; return LineIndex; }()); server.LineIndex = LineIndex; - var LineNode = (function () { + var LineNode = /** @class */ (function () { function LineNode(children) { if (children === void 0) { children = []; } this.children = children; @@ -117910,22 +122238,26 @@ var ts; } }; LineNode.prototype.walk = function (rangeStart, rangeLength, walkFns) { + // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars) var childIndex = 0; var childCharCount = this.children[childIndex].charCount(); + // find sub-tree containing start var adjustedStart = rangeStart; while (adjustedStart >= childCharCount) { - this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0); + this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */); adjustedStart -= childCharCount; childIndex++; childCharCount = this.children[childIndex].charCount(); } + // Case I: both start and end of range in same subtree if ((adjustedStart + rangeLength) <= childCharCount) { - if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2)) { + if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) { return; } } else { - if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1)) { + // Case II: start and end of range in different subtrees (possibly with subtrees in the middle) + if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) { return; } var adjustedLength = rangeLength - (childCharCount - adjustedStart); @@ -117933,7 +122265,7 @@ var ts; var child = this.children[childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { - if (this.execWalk(0, childCharCount, walkFns, childIndex, 3)) { + if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) { return; } adjustedLength -= childCharCount; @@ -117941,22 +122273,26 @@ var ts; childCharCount = this.children[childIndex].charCount(); } if (adjustedLength > 0) { - if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4)) { + if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) { return; } } } + // Process any subtrees after the one containing range end if (walkFns.pre) { var clen = this.children.length; if (childIndex < (clen - 1)) { for (var ej = childIndex + 1; ej < clen; ej++) { - this.skipChild(0, 0, ej, walkFns, 5); + this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */); } } } }; + // Input position is relative to the start of this node. + // Output line number is absolute. LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) { if (this.children.length === 0) { + // Root node might have no children if this is an empty document. return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined }; } for (var _i = 0, _a = this.children; _i < _a.length; _i++) { @@ -117974,9 +122310,15 @@ var ts; lineNumberAccumulator += child.lineCount(); } } + // Skipped all children var leaf = this.lineNumberToInfo(this.lineCount(), 0).leaf; return { oneBasedLine: this.lineCount(), zeroBasedColumn: leaf ? leaf.charCount() : 0, lineText: undefined }; }; + /** + * Input line number is relative to the start of this node. + * Output line number is relative to the child. + * positionAccumulator will be an absolute position once relativeLineNumber reaches 0. + */ LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; @@ -118026,6 +122368,7 @@ var ts; var childIndex = this.findChildIndex(child); var clen = this.children.length; var nodeCount = nodes.length; + // if child is last and there is more room and only one node to place, place it if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) { this.add(nodes[0]); this.updateCounts(); @@ -118074,6 +122417,7 @@ var ts; return splitNodes; } }; + // assume there is room for the item; return true if more room LineNode.prototype.add = function (collection) { this.children.push(collection); ts.Debug.assert(this.children.length <= lineCollectionCapacity); @@ -118086,7 +122430,7 @@ var ts; }; return LineNode; }()); - var LineLeaf = (function () { + var LineLeaf = /** @class */ (function () { function LineLeaf(text) { this.text = text; } @@ -118106,6 +122450,4 @@ var ts; }()); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -//# sourceMappingURL=server.js.map -// Workaround file, please delete once tsbuild understands it's not safe to skip this container -//# sourceMappingURL=tsserverlibrary.js.map \ No newline at end of file +//# sourceMappingURL=tsserverlibrary.out.js.map \ No newline at end of file diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 440e7824b6001..096362cc6a767 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -13,9 +13,8 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ - declare namespace ts { - const versionMajorMinor = "3.0"; + const versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ const version: string; } @@ -369,20 +368,21 @@ declare namespace ts { JSDocAugmentsTag = 293, JSDocClassTag = 294, JSDocCallbackTag = 295, - JSDocParameterTag = 296, - JSDocReturnTag = 297, - JSDocThisTag = 298, - JSDocTypeTag = 299, - JSDocTemplateTag = 300, - JSDocTypedefTag = 301, - JSDocPropertyTag = 302, - SyntaxList = 303, - NotEmittedStatement = 304, - PartiallyEmittedExpression = 305, - CommaListExpression = 306, - MergeDeclarationMarker = 307, - EndOfDeclarationMarker = 308, - Count = 309, + JSDocEnumTag = 296, + JSDocParameterTag = 297, + JSDocReturnTag = 298, + JSDocThisTag = 299, + JSDocTypeTag = 300, + JSDocTemplateTag = 301, + JSDocTypedefTag = 302, + JSDocPropertyTag = 303, + SyntaxList = 304, + NotEmittedStatement = 305, + PartiallyEmittedExpression = 306, + CommaListExpression = 307, + MergeDeclarationMarker = 308, + EndOfDeclarationMarker = 309, + Count = 310, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -409,9 +409,9 @@ declare namespace ts { LastBinaryOperator = 70, FirstNode = 146, FirstJSDocNode = 281, - LastJSDocNode = 302, + LastJSDocNode = 303, FirstJSDocTagNode = 292, - LastJSDocTagNode = 302 + LastJSDocTagNode = 303 } enum NodeFlags { None = 0, @@ -480,7 +480,7 @@ declare namespace ts { } 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; + 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 | ExportDeclaration | EndOfFileToken; type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; @@ -546,8 +546,9 @@ declare namespace ts { } interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; - parent: DeclarationWithTypeParameters | InferTypeNode; + parent: DeclarationWithTypeParameterChildren | InferTypeNode; name: Identifier; + /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ constraint?: TypeNode; default?: TypeNode; expression?: Expression; @@ -617,6 +618,7 @@ declare namespace ts { _objectLiteralBrandBrand: any; name?: PropertyName; } + /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { parent: ObjectLiteralExpression; @@ -750,7 +752,7 @@ declare namespace ts { } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; - parent: SignatureDeclaration; + parent: SignatureDeclaration | JSDocTypeExpression; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -1318,7 +1320,8 @@ declare namespace ts { block: Block; } type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; + type DeclarationWithTypeParameters = DeclarationWithTypeParameterChildren | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; + type DeclarationWithTypeParameterChildren = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; @@ -1437,7 +1440,7 @@ declare namespace ts { kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; } - interface ExportDeclaration extends DeclarationStatement { + interface ExportDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ExportDeclaration; parent: SourceFile | ModuleBlock; /** Will not be assigned in the case of `export * from "foo";` */ @@ -1556,12 +1559,17 @@ declare namespace ts { interface JSDocClassTag extends JSDocTag { kind: SyntaxKind.JSDocClassTag; } + interface JSDocEnumTag extends JSDocTag { + kind: SyntaxKind.JSDocEnumTag; + typeExpression?: JSDocTypeExpression; + } interface JSDocThisTag extends JSDocTag { kind: SyntaxKind.JSDocThisTag; typeExpression?: JSDocTypeExpression; } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; + constraint: TypeNode | undefined; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { @@ -1902,7 +1910,7 @@ declare namespace ts { */ getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; - getTypeAtLocation(node: Node): Type | undefined; + getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; @@ -1934,9 +1942,6 @@ declare namespace ts { getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; - getSuggestionForNonexistentProperty(name: Identifier | string, containingType: Type): string | undefined; - getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; - getSuggestionForNonexistentModule(node: Identifier, target: Symbol): string | undefined; getBaseConstraintOfType(type: Type): Type | undefined; getDefaultFromTypeParameter(type: Type): Type | undefined; /** @@ -2052,6 +2057,7 @@ declare namespace ts { Optional = 16777216, Transient = 33554432, JSContainer = 67108864, + ModuleExports = 134217728, Enum = 384, Variable = 3, Value = 67216319, @@ -2079,8 +2085,6 @@ declare namespace ts { AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, - HasExports = 1955, - HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, ClassMember = 106500 @@ -2110,7 +2114,8 @@ declare namespace ts { Computed = "__computed", Resolving = "__resolving__", ExportEquals = "export=", - Default = "default" + Default = "default", + This = "this" } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -2228,6 +2233,7 @@ declare namespace ts { ReverseMapped = 2048, JsxAttributes = 4096, MarkerType = 8192, + JSLiteral = 16384, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2486,6 +2492,7 @@ declare namespace ts { strictFunctionTypes?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; + stripInternal?: boolean; suppressExcessPropertyErrors?: boolean; suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; @@ -2587,7 +2594,7 @@ declare namespace ts { } interface UpToDateHost { fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date; + getModifiedTime(fileName: string): Date | undefined; getUnchangedTime?(fileName: string): Date | undefined; getLastStatus?(fileName: string): UpToDateStatus | undefined; setLastStatus?(fileName: string, status: UpToDateStatus): void; @@ -2691,7 +2698,7 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date; + getModifiedTime?(fileName: string): Date | undefined; setModifiedTime?(fileName: string, date: Date): void; deleteFile?(fileName: string): void; } @@ -3028,7 +3035,7 @@ declare namespace ts { getCurrentDirectory(): string; getDirectories(path: string): string[]; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - getModifiedTime?(path: string): Date; + getModifiedTime?(path: string): Date | undefined; setModifiedTime?(path: string, time: Date): void; deleteFile?(path: string): void; /** @@ -3186,6 +3193,8 @@ declare namespace ts { * @returns The original parse tree node if found; otherwise, undefined. */ function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier: string): __String; /** * Remove extra underscore from escaped identifier text content. * @@ -3222,6 +3231,8 @@ declare namespace ts { 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 enum tag for the node if present */ + function getJSDocEnumTag(node: Node): JSDocEnumTag | undefined; /** Gets the JSDoc this tag for the node if present */ function getJSDocThisTag(node: Node): JSDocThisTag | undefined; /** Gets the JSDoc return tag for the node if present */ @@ -3243,16 +3254,22 @@ declare namespace ts { */ function getJSDocType(node: Node): TypeNode | undefined; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): ReadonlyArray; /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray; + function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3409,6 +3426,7 @@ declare namespace ts { function isJSDoc(node: Node): node is JSDoc; function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; function isJSDocClassTag(node: Node): node is JSDocClassTag; + function isJSDocEnumTag(node: Node): node is JSDocEnumTag; function isJSDocThisTag(node: Node): node is JSDocThisTag; function isJSDocParameterTag(node: Node): node is JSDocParameterTag; function isJSDocReturnTag(node: Node): node is JSDocReturnTag; @@ -3732,9 +3750,9 @@ declare namespace ts { function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; - function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + /** @deprecated */ function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; - function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + /** @deprecated */ function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; @@ -3743,7 +3761,6 @@ declare namespace ts { function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; 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; - /** @deprecated */ 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; @@ -3759,9 +3776,8 @@ declare namespace ts { function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; - function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + /** @deprecated */ function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; - /** @deprecated */ 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; @@ -4155,10 +4171,14 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; + interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } /** - * Returns the target config filename of a project reference + * Returns the target config filename of a project reference. + * Note: The file might not exist. */ - function resolveProjectReferencePath(host: CompilerHost | UpToDateHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4577,6 +4597,80 @@ declare namespace ts { function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; } +declare namespace ts.server { + type ActionSet = "action::set"; + type ActionInvalidate = "action::invalidate"; + type ActionPackageInstalled = "action::packageInstalled"; + type EventTypesRegistry = "event::typesRegistry"; + type EventBeginInstallTypes = "event::beginInstallTypes"; + type EventEndInstallTypes = "event::endInstallTypes"; + type EventInitializationFailed = "event::initializationFailed"; + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } + interface TypingInstallerResponse { + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + } + interface TypingInstallerRequestWithProjectName { + readonly projectName: string; + } + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { + readonly fileNames: string[]; + readonly projectRootPath: Path; + readonly compilerOptions: CompilerOptions; + readonly typeAcquisition: TypeAcquisition; + readonly unresolvedImports: SortedReadonlyArray; + readonly cachePath?: string; + readonly kind: "discover"; + } + interface CloseProject extends TypingInstallerRequestWithProjectName { + readonly kind: "closeProject"; + } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } + interface PackageInstalledResponse extends ProjectResponse { + readonly kind: ActionPackageInstalled; + readonly success: boolean; + readonly message: string; + } + interface InitializationFailedResponse extends TypingInstallerResponse { + readonly kind: EventInitializationFailed; + readonly message: string; + } + interface ProjectResponse extends TypingInstallerResponse { + readonly projectName: string; + } + interface InvalidateCachedTypings extends ProjectResponse { + readonly kind: ActionInvalidate; + } + interface InstallTypes extends ProjectResponse { + readonly kind: EventBeginInstallTypes | EventEndInstallTypes; + readonly eventId: number; + readonly typingsInstallerVersion: string; + readonly packagesToInstall: ReadonlyArray; + } + interface BeginInstallTypes extends InstallTypes { + readonly kind: EventBeginInstallTypes; + } + interface EndInstallTypes extends InstallTypes { + readonly kind: EventEndInstallTypes; + readonly installSuccess: boolean; + } + interface SetTypings extends ProjectResponse { + readonly typeAcquisition: TypeAcquisition; + readonly compilerOptions: CompilerOptions; + readonly typings: string[]; + readonly unresolvedImports: SortedReadonlyArray; + readonly kind: ActionSet; + } +} declare namespace ts { interface Node { getSourceFile(): SourceFile; @@ -5581,5 +5675,5 @@ declare namespace ts { */ function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions): TransformationResult; } -//# sourceMappingURL=typescriptServices.d.ts.map -export = ts \ No newline at end of file + +export = ts; \ No newline at end of file diff --git a/lib/typescript.js b/lib/typescript.js index 4785ced00f304..78365f95075b7 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -13,7 +13,6 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ - "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { @@ -74,7 +73,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.0"; + ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1685,6 +1684,9 @@ var ts; if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { var candidateNameLowerCase = candidateName.toLowerCase(); if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } return candidate; } if (justCheckExactMatches) { @@ -1895,8 +1897,8 @@ var ts; return function (arg) { return f(arg) || g(arg); }; } ts.or = or; - function assertTypeIsNever(_) { } // tslint:disable-line no-empty - ts.assertTypeIsNever = assertTypeIsNever; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -2358,23 +2360,24 @@ var ts; SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 296] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 297] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 298] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 299] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 300] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 301] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 302] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 303] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 304] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 305] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 306] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 307] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 308] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 309] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -2402,9 +2405,9 @@ var ts; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 302] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 302] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -2732,6 +2735,7 @@ var ts; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; @@ -2765,8 +2769,6 @@ var ts; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasExports"] = 1955] = "HasExports"; - SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; @@ -2820,6 +2822,7 @@ var ts; InternalSymbolName["Resolving"] = "__resolving__"; InternalSymbolName["ExportEquals"] = "export="; InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); /* @internal */ var NodeCheckFlags; @@ -2876,7 +2879,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["UnionOfUnitTypes"] = 67108864] = "UnionOfUnitTypes"; + TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2919,7 +2922,7 @@ var ts; TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotUnit"] = 16749629] = "NotUnit"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2953,6 +2956,7 @@ var ts; ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -3810,52 +3814,80 @@ var ts; */ /*@internal*/ function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); return createDirectoryWatcher; /** * Create the directory watcher for the dirPath. */ function createDirectoryWatcher(dirName, callback) { - var watcher = host.watchDirectory(dirName, function (fileName) { - // Call the actual callback - callback(fileName); - // Iterate through existing children and update the watches if needed - updateChildWatches(result, callback); - }); - var result = { - close: function () { - watcher.close(); - result.childWatches.forEach(ts.closeFileWatcher); - result = undefined; - }, + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { dirName: dirName, - childWatches: ts.emptyArray + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } }; - updateChildWatches(result, callback); - return result; } - function updateChildWatches(watcher, callback) { + function updateChildWatches(dirName, dirPath) { // Iterate through existing children and update the watches if needed - if (watcher) { - watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); } } /** * Watch the directories in the parentDir */ - function watchChildDirectories(parentDir, existingChildWatches, callback) { + function watchChildDirectories(parentDir, existingChildWatches) { var newChildWatches; ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch - return host.filePathComparer(childFullName, host.realpath(childFullName)) === 0 /* EqualTo */ ? childFullName : undefined; - }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); return newChildWatches || ts.emptyArray; /** * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName) { - var result = createDirectoryWatcher(childName, callback); + var result = createDirectoryWatcher(childName); addChildDirectoryWatcher(result); } /** @@ -3882,7 +3914,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; - // TODO: this is used as if it's certainly defined in many places. + // TODO: GH#18217 this is used as if it's certainly defined in many places. ts.sys = (function () { // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual // byte order mark from the specified encoding. Using any other byte order mark does @@ -3991,18 +4023,17 @@ var ts; process.stdout._handle.setBlocking(true); } }, - base64decode: Buffer.from ? function (input) { - return Buffer.from(input, "base64").toString("utf8"); - } : function (input) { - return new Buffer(input, "base64").toString("utf8"); - }, - base64encode: Buffer.from ? function (input) { - return Buffer.from(input).toString("base64"); - } : function (input) { - return new Buffer(input).toString("base64"); - } + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, }; return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } function isFileSystemCaseSensitive() { // win32\win64 are case insensitive platforms if (platform === "win32" || platform === "win64") { @@ -4055,7 +4086,7 @@ var ts; createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : watchDirectoryUsingFsWatch; var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ - filePathComparer: ts.getStringComparer(!useCaseSensitiveFileNames), + useCaseSensitiveFileNames: useCaseSensitiveFileNames, directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, watchDirectory: watchDirectory, @@ -4065,8 +4096,7 @@ var ts; if (recursive) { return watchDirectoryRecursively(directoryName, callback); } - watchDirectory(directoryName, callback); - return undefined; // TODO: GH#18217 + return watchDirectory(directoryName, callback); }; } function createNonPollingWatchFile() { @@ -4749,6 +4779,8 @@ var ts; Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4801,7 +4833,7 @@ var ts; Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), - Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), @@ -5017,6 +5049,9 @@ var ts; Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), 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."), @@ -5103,8 +5138,11 @@ var ts; Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), - _0_was_declared_here: diag(2728, ts.DiagnosticCategory.Error, "_0_was_declared_here_2728", "'{0}' was declared here."), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), 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}'."), @@ -5218,6 +5256,7 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5408,6 +5447,7 @@ var ts; Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5467,12 +5507,14 @@ var ts; Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), - Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Error, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{0}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5502,6 +5544,7 @@ var ts; Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), 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."), @@ -5532,6 +5575,7 @@ var ts; Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), @@ -5542,6 +5586,8 @@ var ts; Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5559,6 +5605,10 @@ var ts; Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), 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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5621,6 +5671,8 @@ var ts; Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), }; })(ts || (ts = {})); var ts; @@ -7374,6 +7426,7 @@ var ts; } function scanJSDocToken() { startPos = tokenPos = pos; + tokenFlags = 0; if (pos >= end) { return token = 1 /* EndOfFileToken */; } @@ -7392,6 +7445,7 @@ var ts; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: return token = 39 /* AsteriskToken */; @@ -7526,6 +7580,7 @@ var ts; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -7634,6 +7689,19 @@ var ts; return undefined; } ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; function forEachEntry(map, callback) { var _a; var iterator = map.entries(); @@ -7857,26 +7925,22 @@ var ts; } ts.nodeIsPresent = nodeIsPresent; /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. + * Prepends statements to an array while taking care of prologue directives. */ - function prependStatements(to, from) { + function addStatementsAfterPrologue(to, from) { if (from === undefined || from.length === 0) return to; - if (to === undefined) - return from.slice(); - var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); - to.unshift.apply(to, from); - if (prologue) { - to.unshift(prologue); + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } } + to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.prependStatements = prependStatements; + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; /** * Determine if the given comment is a triple-slash * @@ -7919,7 +7983,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 303 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8007,11 +8071,6 @@ var ts; return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; - // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' - function escapeLeadingUnderscores(identifier) { - return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); - } - ts.escapeLeadingUnderscores = escapeLeadingUnderscores; // Make an identifier from an external module name by extracting the string after the last "/" and replacing // all non-alphanumeric characters with underscores function makeIdentifierFromModuleName(moduleName) { @@ -8086,6 +8145,10 @@ var ts; return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -8116,6 +8179,18 @@ var ts; } ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 291 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { case 158 /* CallSignature */: case 159 /* ConstructSignature */: @@ -8128,7 +8203,7 @@ var ts; case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: case 240 /* TypeAliasDeclaration */: - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 155 /* Constructor */: @@ -8136,16 +8211,13 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: - case 291 /* JSDocSignature */: return true; default: - ts.assertTypeIsNever(node); + ts.assertType(node); return false; } } - ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { case 247 /* ImportDeclaration */: @@ -8200,11 +8272,11 @@ var ts; return name.escapedText; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return escapeLeadingUnderscores(name.text); + return ts.escapeLeadingUnderscores(name.text); case 147 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } ts.getTextOfPropertyName = getTextOfPropertyName; @@ -8353,9 +8425,7 @@ var ts; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { - return n.kind === 181 /* ImportType */ && - n.argument.kind === 180 /* LiteralType */ && - ts.isStringLiteral(n.argument.literal); + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { @@ -8444,6 +8514,8 @@ var ts; return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case 148 /* TypeParameter */: return node === parent.constraint; + case 301 /* JSDocTemplateTag */: + return node === parent.constraint; case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: case 149 /* Parameter */: @@ -9043,6 +9115,8 @@ var ts; return true; case 209 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 274 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); } @@ -9113,12 +9187,15 @@ var ts; } ts.isStringDoubleQuoted = isStringDoubleQuoted; function getDeclarationOfJSInitializer(node) { - if (!isInJavaScriptFile(node) || !node.parent) { + if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + return undefined; + } name = node.parent.name; decl = node.parent; } @@ -9276,8 +9353,12 @@ var ts; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder function getSpecialPropertyAssignmentKind(expr) { - if (!isInJavaScriptFile(expr) || - expr.operatorToken.kind !== 58 /* EqualsToken */ || + var special = getSpecialPropertyAssignmentKindWorker(expr); + return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getSpecialPropertyAssignmentKindWorker(expr) { + if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } @@ -9288,7 +9369,6 @@ var ts; } return getSpecialPropertyAccessKind(lhs); } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getSpecialPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; @@ -9336,6 +9416,14 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); } @@ -9412,7 +9500,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 301 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9700,7 +9788,10 @@ var ts; } else { var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + return ts.isBinaryExpression(binExp) && + getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name; } } default: @@ -9903,12 +9994,10 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isStringOrNumericLiteral(node) { - var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 8 /* NumericLiteral */; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); } - ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; /** * A declaration has a dynamic name if both of the following are true: * 1. The declaration has a computed property name @@ -9923,7 +10012,7 @@ var ts; ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { return name.kind === 147 /* ComputedPropertyName */ && - !isStringOrNumericLiteral(name.expression) && + !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -9937,22 +10026,24 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 /* Identifier */) { - return name.escapedText; - } - if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(name.text); - } - if (name.kind === 147 /* ComputedPropertyName */) { - var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(nameExpression.text); - } + switch (name.kind) { + case 71 /* Identifier */: + return name.escapedText; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 147 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); } - return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { @@ -9972,7 +10063,7 @@ var ts; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : escapeLeadingUnderscores(node.text); + return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -10093,7 +10184,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return 0; case 206 /* SpreadElement */: return 1; @@ -10471,27 +10562,30 @@ var ts; return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; - function getOwnEmitOutputFilePath(sourceFile, host, extension) { + function getOwnEmitOutputFilePath(fileName, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; if (compilerOptions.outDir) { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); } else { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); } return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; - function getDeclarationEmitOutputFilePath(sourceFile, host) { - var options = host.getCompilerOptions(); + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } - ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; /** * Gets the source files that are expected to have an emit output. * @@ -10523,14 +10617,17 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - var commonSourceDirectory = host.getCommonSourceDirectory(); - var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } - ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); @@ -10603,7 +10700,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 156 /* GetAccessor */ || member.kind === 157 /* SetAccessor */) + if (ts.isAccessor(member) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -10637,7 +10734,10 @@ var ts; * parsed in a JavaScript file, gets the type annotation from JSDoc. */ function getEffectiveTypeAnnotationNode(node) { - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); + var type = node.type; + if (type || !isInJavaScriptFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; function getTypeAnnotationNode(node) { @@ -10649,27 +10749,11 @@ var ts; * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { - if (ts.isJSDocSignature(node)) { - return node.type && node.type.typeExpression && node.type.typeExpression.type; - } - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - /** - * Gets the effective type parameters. If the node was parsed in a - * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. - */ - function getEffectiveTypeParameterDeclarations(node) { - if (ts.isJSDocSignature(node)) { - return ts.emptyArray; - } - if (isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); - return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); - } - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); - } - ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); } @@ -11436,7 +11520,9 @@ var ts; return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; case 202 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; - return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); default: @@ -11966,6 +12052,11 @@ var ts; return undefined; } ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; /** * Remove extra underscore from escaped identifier text content. * @@ -12051,8 +12142,8 @@ var ts; switch (declaration.kind) { case 71 /* Identifier */: return declaration; - case 302 /* JSDocPropertyTag */: - case 296 /* JSDocParameterTag */: { + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: { var name = declaration.name; if (name.kind === 146 /* QualifiedName */) { return name.right; @@ -12071,7 +12162,7 @@ var ts; return undefined; } } - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); case 252 /* ExportAssignment */: { var expression = declaration.expression; @@ -12156,6 +12247,11 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; /** Gets the JSDoc this tag for the node if present */ function getJSDocThisTag(node) { return getFirstJSDocTag(node, ts.isJSDocThisTag); @@ -12201,14 +12297,27 @@ var ts; } ts.getJSDocType = getJSDocType; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node) { var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } } ts.getJSDocReturnType = getJSDocReturnType; /** Get all JSDoc tags related to a node, including those on parent nodes. */ @@ -12232,6 +12341,28 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -12469,7 +12600,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 305 /* PartiallyEmittedExpression */) { + while (node.kind === 306 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -12872,36 +13003,40 @@ var ts; return node.kind === 294 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 296 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 298 /* JSDocThisTag */; + return node.kind === 299 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 296 /* JSDocParameterTag */; + return node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 297 /* JSDocReturnTag */; + return node.kind === 298 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 299 /* JSDocTypeTag */; + return node.kind === 300 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 300 /* JSDocTemplateTag */; + return node.kind === 301 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 301 /* JSDocTypedefTag */; + return node.kind === 302 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 302 /* JSDocPropertyTag */; + return node.kind === 303 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 302 /* JSDocPropertyTag */ || node.kind === 296 /* JSDocParameterTag */; + return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { @@ -12924,7 +13059,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 303 /* SyntaxList */; + return n.kind === 304 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13389,8 +13524,8 @@ var ts; case 206 /* SpreadElement */: case 210 /* AsExpression */: case 208 /* OmittedExpression */: - case 306 /* CommaListExpression */: - case 305 /* PartiallyEmittedExpression */: + case 307 /* CommaListExpression */: + case 306 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13404,12 +13539,12 @@ var ts; ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 305 /* PartiallyEmittedExpression */; + return node.kind === 306 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 304 /* NotEmittedStatement */; + return node.kind === 305 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13520,9 +13655,9 @@ var ts; || kind === 240 /* TypeAliasDeclaration */ || kind === 148 /* TypeParameter */ || kind === 235 /* VariableDeclaration */ - || kind === 301 /* JSDocTypedefTag */ + || kind === 302 /* JSDocTypedefTag */ || kind === 295 /* JSDocCallbackTag */ - || kind === 302 /* JSDocPropertyTag */; + || kind === 303 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { return kind === 237 /* FunctionDeclaration */ @@ -13557,14 +13692,14 @@ var ts; || kind === 217 /* VariableStatement */ || kind === 222 /* WhileStatement */ || kind === 229 /* WithStatement */ - || kind === 304 /* NotEmittedStatement */ - || kind === 308 /* EndOfDeclarationMarker */ - || kind === 307 /* MergeDeclarationMarker */; + || kind === 305 /* NotEmittedStatement */ + || kind === 309 /* EndOfDeclarationMarker */ + || kind === 308 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 300 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -13659,7 +13794,7 @@ var ts; /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 302 /* LastJSDocNode */; + return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ @@ -13670,7 +13805,7 @@ var ts; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 302 /* LastJSDocTagNode */; + return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -13695,45 +13830,6 @@ var ts; return !!node.type; } ts.hasType = hasType; - /* True if the node could have a type node a `.type` */ - /* @internal */ - function couldHaveType(node) { - switch (node.kind) { - case 149 /* Parameter */: - case 151 /* PropertySignature */: - case 152 /* PropertyDeclaration */: - case 153 /* MethodSignature */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 175 /* ParenthesizedType */: - case 177 /* TypeOperator */: - case 179 /* MappedType */: - case 192 /* TypeAssertionExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 210 /* AsExpression */: - case 235 /* VariableDeclaration */: - case 237 /* FunctionDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 281 /* JSDocTypeExpression */: - case 284 /* JSDocNullableType */: - case 285 /* JSDocNonNullableType */: - case 286 /* JSDocOptionalType */: - case 287 /* JSDocFunctionType */: - case 288 /* JSDocVariadicType */: - return true; - } - return false; - } - ts.couldHaveType = couldHaveType; /** True if has initializer node attached to it. */ /* @internal */ function hasInitializer(node) { @@ -13747,18 +13843,7 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - switch (node.kind) { - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return true; - default: - return false; - } + return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ @@ -14016,7 +14101,7 @@ var ts; } ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { - return !!(options.declaration && options.declarationMap); + return !!(getEmitDeclarations(options) && options.declarationMap); } ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { @@ -14036,6 +14121,14 @@ var ts; return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + if (oldOptions === newOptions) { + return false; + } + return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || + (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14200,6 +14293,12 @@ var ts; return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); } ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; function isUrl(path) { return getEncodedRootLength(path) < 0; } @@ -15052,6 +15151,100 @@ var ts; return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); } ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; })(ts || (ts = {})); var ts; (function (ts) { @@ -15469,7 +15662,7 @@ var ts; return visitNode(cbNode, node.expression); case 256 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 258 /* JsxElement */: return visitNode(cbNode, node.openingElement) || @@ -15509,8 +15702,8 @@ var ts; visitNode(cbNode, node.type); case 289 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15519,15 +15712,15 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 297 /* JSDocReturnTag */: + case 298 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); case 293 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 300 /* JSDocTemplateTag */: - return visitNodes(cbNode, cbNodes, node.typeParameters); - case 301 /* JSDocTypedefTag */: + case 301 /* JSDocTemplateTag */: + return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); + case 302 /* JSDocTypedefTag */: if (node.typeExpression && node.typeExpression.kind === 281 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || @@ -15540,13 +15733,15 @@ var ts; case 295 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 298 /* JSDocThisTag */: + case 299 /* JSDocThisTag */: + return visitNode(cbNode, node.typeExpression); + case 296 /* JSDocEnumTag */: return visitNode(cbNode, node.typeExpression); case 291 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || + ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); case 290 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { @@ -15556,7 +15751,7 @@ var ts; } } return; - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -16405,7 +16600,7 @@ var ts; return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); @@ -16428,7 +16623,7 @@ var ts; return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: if (token() === 26 /* CommaToken */) { @@ -16438,13 +16633,15 @@ var ts; case 11 /* ArgumentExpressions */: return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: - return isStartOfParameter(); - case 19 /* TypeArguments */: - case 20 /* TupleElementTypes */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: return token() === 26 /* CommaToken */ || isStartOfType(); - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return isHeritageClause(); - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; @@ -16509,7 +16706,7 @@ var ts; case 6 /* EnumMembers */: case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return token() === 18 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; @@ -16517,24 +16714,25 @@ var ts; return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: return token() === 22 /* CloseBracketToken */; + case 17 /* JSDocParameters */: case 16 /* Parameters */: - case 17 /* RestProperties */: + case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token return token() !== 26 /* CommaToken */; - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; case 13 /* JsxAttributes */: return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; @@ -16567,7 +16765,7 @@ var ts; } // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 23 /* Count */; kind++) { + for (var kind = 0; kind < 24 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; @@ -16679,24 +16877,25 @@ var ts; return isReusableTypeMember(node); case 8 /* VariableDeclarations */: return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -16704,7 +16903,7 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. @@ -16854,7 +17053,7 @@ var ts; case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected; case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; - case 17 /* RestProperties */: // fallthrough + case 18 /* RestProperties */: // fallthrough case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; @@ -16865,12 +17064,13 @@ var ts; case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected; case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; + case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected; case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 18 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; - case 19 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 20 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; - case 21 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; - case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; + case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; + case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; + case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` @@ -17070,7 +17270,7 @@ var ts; var node = createNode(162 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } return finishNode(node); } @@ -17168,7 +17368,7 @@ var ts; } function parseJSDocType() { var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); - var type = parseType(); + var type = parseTypeOrTypePredicate(); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -17214,7 +17414,7 @@ var ts; } function parseTypeParameters() { if (token() === 27 /* LessThanToken */) { - return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } } function parseParameterType() { @@ -17223,12 +17423,12 @@ var ts; } return undefined; } - function isStartOfParameter() { + function isStartOfParameter(isJSDocParameter) { return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 /* AtToken */ || - isStartOfType(/*inStartOfParameter*/ true); + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { var node = createNodeWithJSDoc(149 /* Parameter */); @@ -17314,7 +17514,9 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1 /* Yield */)); setAwaitContext(!!(flags & 2 /* Await */)); - signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return parseExpected(20 /* CloseParenToken */); @@ -17552,7 +17754,7 @@ var ts; } function parseTupleType() { var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { @@ -17705,6 +17907,8 @@ var ts; case 126 /* InferKeyword */: case 91 /* ImportKeyword */: return true; + case 89 /* FunctionKeyword */: + return !inStartOfParameter; case 38 /* MinusToken */: return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19 /* OpenParenToken */: @@ -17717,7 +17921,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); @@ -18211,8 +18415,9 @@ var ts; return 1 /* True */; } // If we had "(" followed by something that's not an identifier, - // then this definitely doesn't look like a lambda. - if (!isIdentifier()) { + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 99 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { @@ -19047,7 +19252,7 @@ var ts; } else { var argument = allowInAnd(parseExpression); - if (ts.isStringOrNumericLiteral(argument)) { + if (ts.isStringOrNumericLiteralLike(argument)) { argument.text = internIdentifier(argument.text); } indexedAccess.argumentExpression = argument; @@ -19118,7 +19323,7 @@ var ts; if (!parseOptional(27 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; @@ -20270,7 +20475,7 @@ var ts; // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } if (isHeritageClause()) { - return parseList(21 /* HeritageClauses */, parseHeritageClause); + return parseList(22 /* HeritageClauses */, parseHeritageClause); } return undefined; } @@ -20291,7 +20496,7 @@ var ts; } function tryParseTypeArguments() { return token() === 27 /* LessThanToken */ - ? parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) : undefined; } function isHeritageClause() { @@ -20517,7 +20722,7 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { @@ -20631,13 +20836,14 @@ var ts; ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; - ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; // Number of parsing contexts + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -20754,7 +20960,7 @@ var ts; switch (token()) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -20814,7 +21020,7 @@ var ts; nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return createJSDocComment(); }); function removeLeadingNewlines(comments) { @@ -20822,8 +21028,8 @@ var ts; comments.shift(); } } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { comments.pop(); } } @@ -20855,13 +21061,30 @@ var ts; nextJSDocToken(); } } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 39 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } function parseTag(indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": @@ -20875,6 +21098,9 @@ var ts; case "this": tag = parseThisTag(atToken, tagName); break; + case "enum": + tag = parseEnumTag(atToken, tagName); + break; case "arg": case "argument": case "param": @@ -20972,7 +21198,7 @@ var ts; tok = nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { @@ -20995,7 +21221,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespace(); + skipWhitespaceOrAsterisk(); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -21029,15 +21255,15 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespace(); + skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(302 /* JSDocPropertyTag */, atToken.pos) : - createNode(296 /* JSDocParameterTag */, atToken.pos); + createNode(303 /* JSDocPropertyTag */, atToken.pos) : + createNode(297 /* JSDocParameterTag */, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -21063,7 +21289,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) { + if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } } @@ -21079,20 +21305,20 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 297 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(297 /* JSDocReturnTag */, atToken.pos); + var result = createNode(298 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 299 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(299 /* JSDocTypeTag */, atToken.pos); + var result = createNode(300 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); @@ -21133,7 +21359,15 @@ var ts; return finishNode(tag); } function parseThisTag(atToken, tagName) { - var tag = createNode(298 /* JSDocThisTag */, atToken.pos); + var tag = createNode(299 /* JSDocThisTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(atToken, tagName) { + var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); @@ -21143,7 +21377,7 @@ var ts; function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(301 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); @@ -21156,12 +21390,12 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = scanner.getStartPos(); + var start_3 = atToken.pos; while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 299 /* JSDocTypeTag */) { + if (child.kind === 300 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21224,7 +21458,7 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(57 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 297 /* JSDocReturnTag */) { + if (tag && tag.kind === 298 /* JSDocReturnTag */) { return tag; } } @@ -21269,7 +21503,7 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) && + if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -21338,16 +21572,14 @@ var ts; skipWhitespace(); var typeParameter = createNode(148 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); - skipWhitespace(); finishNode(typeParameter); + skipWhitespace(); typeParameters.push(typeParameter); } while (parseOptionalJsdoc(26 /* CommaToken */)); - if (constraint) { - ts.first(typeParameters).constraint = constraint.type; - } - var result = createNode(300 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; + result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); return result; @@ -21873,9 +22105,11 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + ts.isDeclarationFileName = isDeclarationFileName; /*@internal*/ function processCommentPragmas(context, sourceText) { var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); @@ -22419,13 +22653,15 @@ var ts; { name: "noImplicitAny", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type }, { name: "strictNullChecks", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks @@ -22433,6 +22669,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types @@ -22440,6 +22677,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes @@ -22447,6 +22685,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, @@ -22454,6 +22693,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file @@ -22462,6 +22702,7 @@ var ts; { name: "noUnusedLocals", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_locals, @@ -22469,6 +22710,7 @@ var ts; { name: "noUnusedParameters", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_parameters, @@ -22476,6 +22718,7 @@ var ts; { name: "noImplicitReturns", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value @@ -22483,6 +22726,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement @@ -22553,12 +22797,14 @@ var ts; { name: "allowSyntheticDefaultImports", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, { name: "esModuleInterop", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports @@ -22734,6 +22980,7 @@ var ts; { name: "noImplicitUseStrict", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output }, @@ -22772,24 +23019,28 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels }, { name: "allowUnreachableCode", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code }, { name: "suppressExcessPropertyErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, }, { name: "suppressImplicitAnyIndexErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, @@ -22808,6 +23059,7 @@ var ts; { name: "noStrictGenericChecks", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, }, @@ -23329,9 +23581,10 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); - var option = knownOptions ? knownOptions.get(keyText) : undefined; - if (extraKeyDiagnosticMessage && !option) { + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); @@ -24406,9 +24659,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -24637,9 +24890,7 @@ var ts; return perFolderCache; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; // TODO: GH#18217 - } + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { perModuleNameCache = createPerModuleNameCache(); @@ -24671,41 +24922,45 @@ var ts; return; } directoryPathMap.set(path, result); - var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); // find common prefix between directory and resolved file name - // this common prefix should be the shorted path that has the same resolution + // this common prefix should be the shortest path that has the same resolution // directory: /a/b/c/d/e // resolvedFileName: /a/b/foo.d.ts - var commonPrefix = getCommonPrefix(path, resolvedFileName); + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); var current = path; - while (true) { + while (current !== commonPrefix) { var parent = ts.getDirectoryPath(current); if (parent === current || directoryPathMap.has(parent)) { break; } directoryPathMap.set(parent, result); current = parent; - if (current === commonPrefix) { - break; - } } } function getCommonPrefix(directory, resolution) { - if (resolution === undefined) { - return undefined; - } var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); // find first position where directory and resolution differs var i = 0; - while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { i++; } - // find last directory separator before position i - var sep = directory.lastIndexOf(ts.directorySeparator, i); - if (sep < 0) { + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { return undefined; } - return directory.substr(0, sep); + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { + return undefined; + } + return directory.substr(0, Math.max(sep, rootLength)); } } } @@ -24754,10 +25009,9 @@ var ts; } if (perFolderCache) { perFolderCache.set(moduleName, result); - // put result in per-module name cache - var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); - if (perModuleNameCache) { - perModuleNameCache.set(containingDirectory, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); } } } @@ -24982,15 +25236,15 @@ var ts; tryResolve(Extensions.JavaScript) || (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { @@ -25000,17 +25254,13 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - var originalPath = void 0; - if (!compilerOptions.preserveSymlinks && resolvedValue) { - originalPath = resolvedValue.path; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - if (path === originalPath) { - originalPath = undefined; - } - resolvedValue = __assign({}, resolvedValue, { path: path }); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -25063,7 +25313,8 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } - var nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -25077,11 +25328,11 @@ var ts; */ function parseNodeModuleFromPath(resolved) { var path = ts.normalizePath(resolved.path); - var idx = path.lastIndexOf(nodeModulesPathPart); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; } - var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); @@ -25424,7 +25675,7 @@ var ts; trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -25434,17 +25685,17 @@ var ts; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*originalPath*/ undefined, /*isExternalLibraryImport*/ false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -25479,7 +25730,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*originalPath*/ undefined, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -25687,10 +25938,10 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; symbol.declarations = ts.append(symbol.declarations, node); - if (symbolFlags & 1955 /* HasExports */ && !symbol.exports) { + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } - if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } if (symbolFlags & 67216319 /* Value */) { @@ -25717,7 +25968,7 @@ var ts; if (name.kind === 147 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression)) { + if (ts.isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -25762,7 +26013,7 @@ var ts; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); // TODO: GH#18217 + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); } /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @@ -25833,8 +26084,10 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; } if (symbol.declarations && symbol.declarations.length) { // If the current node is a default export of some sort, then check if @@ -25842,6 +26095,7 @@ var ts; // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } else { // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. @@ -25851,13 +26105,15 @@ var ts; if (symbol.declarations && symbol.declarations.length && (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } } } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); symbol = createSymbol(0 /* None */, name); } } @@ -26128,7 +26384,7 @@ var ts; case 189 /* CallExpression */: bindCallExpressionFlow(node); break; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; @@ -26153,6 +26409,7 @@ var ts; case 71 /* Identifier */: case 99 /* ThisKeyword */: case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return isNarrowableReference(expr); case 189 /* CallExpression */: return hasNarrowableArgument(expr); @@ -26166,10 +26423,11 @@ var ts; return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || - expr.kind === 99 /* ThisKeyword */ || - expr.kind === 97 /* SuperKeyword */ || - expr.kind === 187 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -26605,7 +26863,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -26894,7 +27152,7 @@ var ts; case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: case 287 /* JSDocFunctionType */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: case 240 /* TypeAliasDeclaration */: case 179 /* MappedType */: @@ -27232,13 +27490,26 @@ var ts; errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } - function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); if (isError) { file.bindDiagnostics.push(diag); } @@ -27358,12 +27629,19 @@ var ts; } return checkStrictModeIdentifier(node); case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } + if (ts.isInJavaScriptFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(container, "module")) { + declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + } break; case 202 /* BinaryExpression */: var specialKind = ts.getSpecialPropertyAssignmentKind(node); @@ -27405,6 +27683,8 @@ var ts; return checkStrictModePrefixUnaryExpression(node); case 229 /* WithStatement */: return checkStrictModeWithStatement(node); + case 231 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); case 176 /* ThisType */: seenThisKeyword = true; return; @@ -27508,7 +27788,7 @@ var ts; // falls through case 243 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: if (node.parent.kind === 291 /* JSDocSignature */) { return bindParameter(node); } @@ -27516,13 +27796,13 @@ var ts; break; } // falls through - case 302 /* JSDocPropertyTag */: + case 303 /* JSDocPropertyTag */: var propTag = node; var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } @@ -27727,6 +28007,11 @@ var ts; } function bindSpecialPropertyAssignment(node) { var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } // Fix up parent pointers since we're going to use these nodes before we bind into them node.left.parent = node; node.right.parent = node; @@ -27910,7 +28195,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 296 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -28034,18 +28319,48 @@ var ts; // - node is not block scoped variable statement and at least one variable declaration has initializer // Rationale: we don't want to report errors on non-initialized var's since they are hoisted // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var isError = ts.unreachableCodeIsError(options) && + var isError_1 = ts.unreachableCodeIsError(options) && !(node.flags & 4194304 /* Ambient */) && (!ts.isVariableStatement(node) || !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || node.declarationList.declarations.some(function (d) { return !!d.initializer; })); - errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); } } } return true; } } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return true; + case 242 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 241 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || @@ -28619,7 +28934,7 @@ var ts; break; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; @@ -28896,7 +29211,7 @@ var ts; return 940049729 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: case 193 /* ParenthesizedExpression */: case 97 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; @@ -28920,7 +29235,7 @@ var ts; /** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -28996,7 +29311,7 @@ var ts; ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { - visitType(getConstraintFromTypeParameter(type)); + visitType(getConstraintOfTypeParameter(type)); } function visitUnionOrIntersectionType(type) { ts.forEach(type.types, visitType); @@ -29068,7 +29383,7 @@ var ts; } var t = getTypeOfSymbol(symbol); visitType(t); // Should handle members on classes and such - if (symbol.flags & 1955 /* HasExports */) { + if (symbol.exports) { symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { @@ -29158,7 +29473,6 @@ var ts; undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); - var moduleSymbol = createSymbol(4 /* Property */, "module"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; // for public members that accept a Node or one of its subtypes, we must guard against @@ -29202,6 +29516,7 @@ var ts; return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, getReturnTypeOfSignature: getReturnTypeOfSignature, getNullableType: getNullableType, getNonNullableType: getNonNullableType, @@ -29270,6 +29585,10 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); @@ -29280,12 +29599,11 @@ var ts; }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { - var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); - apparentArgumentCount = theArgumentCount; - var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; - apparentArgumentCount = undefined; - return res; + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); }, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); @@ -29322,7 +29640,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); @@ -29365,7 +29683,7 @@ var ts; getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentModule: function (node, target) { return getSuggestionForNonexistentModule(node, target); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -29384,6 +29702,9 @@ var ts; return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } var diagnostics; try { // Record the cancellation token so it can be checked later on during checkSourceElement. @@ -29403,8 +29724,8 @@ var ts; cancellationToken = undefined; } function addUnusedDiagnostics() { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { - if (!unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } }); @@ -29420,6 +29741,13 @@ var ts; } } }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } var tupleTypes = ts.createMap(); var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); @@ -29475,7 +29803,6 @@ var ts; var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); @@ -29647,7 +29974,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30089,6 +30416,7 @@ var ts; // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) // or if usage is in a type context: // 1. inside a type query (typeof in type position) + // 2. inside a jsdoc comment if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; @@ -30098,7 +30426,7 @@ var ts; return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { @@ -30381,7 +30709,7 @@ var ts; location = location.parent; } break; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); @@ -30415,10 +30743,6 @@ var ts; if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } - if (ts.isIdentifier(originalLocation) && ts.isPropertyAccessExpression(originalLocation.parent) && - originalLocation.escapedText === "module" && originalLocation.parent.name.escapedText === "exports") { - return moduleSymbol; - } } } if (!result) { @@ -30431,9 +30755,13 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { - suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } } if (!suggestion) { @@ -30642,7 +30970,7 @@ var ts; ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } } @@ -30786,7 +31114,7 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } } } @@ -30821,9 +31149,13 @@ var ts; if (!symbol) { var moduleName = getFullyQualifiedName(moduleSymbol); var declarationName = ts.declarationNameToString(name); - var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); @@ -31145,6 +31477,12 @@ var ts; var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -31157,8 +31495,8 @@ var ts; var errorInfo = packageId ? ts.chainDiagnosticMessages( /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0 - : ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)) + ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 + : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } @@ -31303,13 +31641,13 @@ var ts; } function getExportsOfModuleWorker(moduleSymbol) { var visitedSymbols = []; - // A module defined by an 'export=' consists on one export that needs to be resolved + // A module defined by an 'export=' consists of one export that needs to be resolved moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; // 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 & 1955 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { return; } var symbols = ts.cloneMap(symbol.exports); @@ -31354,17 +31692,25 @@ var ts; * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` */ - function getContainerOfSymbol(symbol) { + function getContainersOfSymbol(symbol, enclosingDeclaration) { var container = getParentOfSymbol(symbol); if (container) { - return container; + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + } + return ts.append(additionalContainers, container); } - var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); - if (!candidate) { + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { return undefined; } - var alias = getAliasForSymbolInContainer(candidate, symbol); - return alias ? candidate : undefined; + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { @@ -31388,9 +31734,7 @@ var ts; } } function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); @@ -31615,6 +31959,54 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -31625,55 +32017,20 @@ var ts; */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, - }; - } - return hasAccessibleDeclarations; - } - else { - if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { - // Any meaning of a module symbol is always accessible via an `import` type - return { - accessibility: 0 /* Accessible */ - }; - } - } - // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. - // It could be a qualified symbol and hence verify the path - // e.g.: - // module m { - // export class c { - // } - // } - // const x: typeof m.c - // In the above example when we start with checking if typeof m.c symbol is accessible, - // we are going to see if c can be accessed in scope directly. - // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible - // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getContainerOfSymbol(symbol); + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { accessibility: 2 /* CannotBeNamed */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), errorModuleName: symbolToString(symbolExternalModule) }; } @@ -31681,14 +32038,14 @@ var ts; // Just a local name that is not accessible return { accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 /* Accessible */ }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); @@ -31809,7 +32166,8 @@ var ts; function typeToString(type, enclosingDeclaration, flags, writer) { if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -31817,7 +32175,7 @@ var ts; var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } @@ -31862,11 +32220,17 @@ var ts; tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, - inferTypeParameters: undefined + inferTypeParameters: undefined, + approximateLength: 0 }; var resultingNode = cb(context); return context.encounteredError ? undefined : resultingNode; } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + } function typeToTypeNodeHelper(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); @@ -31878,66 +32242,83 @@ var ts; return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { return ts.createKeywordTypeNode(142 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(137 /* StringKeyword */); } if (type.flags & 8 /* Number */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(134 /* NumberKeyword */); } if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (type.flags & (64 /* StringLiteral */)) { + if (type.flags & 64 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & (128 /* NumberLiteral */)) { + if (type.flags & 128 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 256 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 2048 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } + context.approximateLength += 13; return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); } if (type.flags & 4096 /* Void */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(105 /* VoidKeyword */); } if (type.flags & 8192 /* Undefined */) { + context.approximateLength += 9; return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); } if (type.flags & 16384 /* Null */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(95 /* NullKeyword */); } if (type.flags & 32768 /* Never */) { + context.approximateLength += 5; return ts.createKeywordTypeNode(131 /* NeverKeyword */); } if (type.flags & 1024 /* ESSymbol */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(138 /* SymbolKeyword */); } if (type.flags & 16777216 /* NonPrimitive */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(135 /* ObjectKeyword */); } if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { @@ -31949,6 +32330,7 @@ var ts; context.tracker.reportInaccessibleThisError(); } } + context.approximateLength += 4; return ts.createThis(); } var objectFlags = ts.getObjectFlags(type); @@ -31958,6 +32340,7 @@ var ts; } if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && @@ -31966,7 +32349,9 @@ var ts; ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { - return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol @@ -31981,7 +32366,7 @@ var ts; } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; - var typeNodes = mapToTypeNodes(types, context); + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; @@ -32000,12 +32385,14 @@ var ts; } if (type.flags & 1048576 /* Index */) { var indexedType = type.type; + context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 2097152 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } if (type.flags & 4194304 /* Conditional */) { @@ -32016,6 +32403,7 @@ var ts; context.inferTypeParameters = saveInferTypeParameters; var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 8388608 /* Substitution */) { @@ -32038,6 +32426,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { @@ -32046,7 +32435,7 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); @@ -32065,6 +32454,7 @@ var ts; return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); } else { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } } @@ -32106,6 +32496,7 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { @@ -32124,6 +32515,7 @@ var ts; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function typeReferenceToTypeNode(type) { @@ -32240,6 +32632,9 @@ var ts; return ids; } function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; @@ -32262,8 +32657,10 @@ var ts; if (!properties) { return typeElements; } + var i = 0; for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + i++; if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { if (propertySymbol.flags & 4194304 /* Prototype */) { continue; @@ -32272,61 +32669,96 @@ var ts; context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); } } - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? - anyType : getTypeOfSymbol(propertySymbol); - var saveEnclosingDeclaration = context.enclosingDeclaration; - context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } - } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); - context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; - if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { - var signatures = getSignaturesOfType(propertyType, 0 /* Call */); - for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { - var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); - } - typeElements.push(methodDeclaration); - } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); } - else { - var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; - var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined); - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); - } - typeElements.push(propertySignature); + } + } + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); } + typeElements.push(methodDeclaration); } - return typeElements.length ? typeElements : undefined; + } + else { + var savedFlags = context.flags; + context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); } } - function mapToTypeNodes(types, context) { + function mapToTypeNodes(types, context, isBareList) { if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } var result = []; + var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -32348,6 +32780,7 @@ var ts; if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } + context.approximateLength += (name.length + 4); return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } @@ -32386,6 +32819,7 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { @@ -32407,14 +32841,14 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 296 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32436,6 +32870,7 @@ var ts; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); @@ -32465,16 +32900,18 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); - var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents)) { + for (var _i = 0, _a = parents; _i < _a.length; _i++) { + var parent = _a[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } } } } @@ -32484,10 +32921,12 @@ var ts; if ( // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } return [symbol]; } } @@ -32542,24 +32981,26 @@ var ts; } } } - return symbol.escapedName.substring(1, symbol.escapedName.length - 1); - } - else { - if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { - // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); - var links = getSymbolLinks(symbol); - var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); - if (!specifier) { - specifier = ts.flatten(ts.moduleSpecifiers.getModuleSpecifiers(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, context.tracker.moduleResolverHost.getSourceFiles(), // TODO: GH#18217 - { importModuleSpecifierPreference: "non-relative" }))[0]; - links.specifierCache = links.specifierCache || ts.createMap(); - links.specifierCache.set(contextFile.path, specifier); + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - return specifier; + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module @@ -32568,7 +33009,11 @@ var ts; // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); - var lit = ts.createLiteralTypeNode(ts.createLiteral(getSpecifierForModuleSymbol(chain[0], context))); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") if (!nonRootParts || ts.isEntityName(nonRootParts)) { if (nonRootParts) { var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; @@ -32602,6 +33047,7 @@ var ts; context.flags |= 16777216 /* InInitialEntityName */; } var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } @@ -32816,7 +33262,7 @@ var ts; function determineIfDeclarationIsVisible() { switch (node.kind) { case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); @@ -32969,23 +33415,19 @@ var ts; return -1; } function hasType(target, propertyName) { - if (propertyName === 0 /* Type */) { - return !!getSymbolLinks(target).type; - } - if (propertyName === 2 /* DeclaredType */) { - return !!getSymbolLinks(target).declaredType; - } - if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return !!target.resolvedBaseConstructorType; - } - if (propertyName === 3 /* ResolvedReturnType */) { - return !!target.resolvedReturnType; - } - if (propertyName === 4 /* ResolvedBaseConstraint */) { - var bc = target.resolvedBaseConstraint; - return !!bc && bc !== circularConstraintType; - } - return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + } + return ts.Debug.assertNever(propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -33032,7 +33474,7 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); @@ -33050,10 +33492,9 @@ var ts; } for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; - var inNamesToRemove = names.has(prop.escapedName); - var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); - var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); - if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { + if (!names.has(prop.escapedName) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { members.set(prop.escapedName, getNonReadonlySymbol(prop)); } } @@ -33261,17 +33702,17 @@ var ts; } } // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.escapedName === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } + else if (ts.isInJavaScriptFile(declaration)) { + var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); + if (expandoType) { + return expandoType; + } + } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); @@ -33289,96 +33730,46 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); if (specialDeclaration) { - return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var tag = ts.getJSDocTypeTag(specialDeclaration); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); + return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); } - var types = []; - var constructorTypes; var definedInConstructor = false; var definedInMethod = false; - var jsDocType; - var _loop_4 = function (declaration) { - var declarationInConstructor = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; var expression = ts.isBinaryExpression(declaration) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { - return { value: errorType }; + return errorType; } var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); if (special === 4 /* ThisProperty */) { - var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); - // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. - // Function expressions that are assigned to the prototype count as methods. - declarationInConstructor = thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 237 /* FunctionDeclaration */ || - (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); - if (declarationInConstructor) { + if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } else { definedInMethod = true; } } - // If there is a JSDoc type, use it - var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type_1) { - var declarationType = getWidenedType(type_1); - if (!jsDocType) { - jsDocType = declarationType; - } - else if (jsDocType !== errorType && declarationType !== errorType && - !isTypeIdenticalTo(jsDocType, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { - errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); - } - } - else if (!jsDocType && ts.isBinaryExpression(expression)) { - // If we don't have an explicit JSDoc type, get the type from the expression. - var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); - if (ts.getObjectFlags(type_2) & 16 /* Anonymous */ && - special === 2 /* ModuleExports */ && - symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type_2); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); - symbol.exports.forEach(function (s, name) { - if (members_3.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); - } - else { - members_3.set(name, s); - } - }); - type_2 = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); - } - var anyedType = type_2; - if (isEmptyArrayLiteralType(type_2)) { - anyedType = anyArrayType; - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } - } - types.push(anyedType); - if (declarationInConstructor) { - (constructorTypes || (constructorTypes = [])).push(anyedType); - } + jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!jsdocType) { + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); } - }; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var state_2 = _loop_4(declaration); - if (typeof state_2 === "object") - return state_2.value; } - var type = jsDocType; + var type = jsdocType; if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfSpecialPropertyOfBaseType(symbol); @@ -33399,6 +33790,91 @@ var ts; } return widened; } + function getJSExpandoObjectType(decl, symbol, init) { + if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 131072 /* Object */ && + special === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 155 /* Constructor */ || + thisContainer.kind === 237 /* FunctionDeclaration */ || + (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } /** check for definition in base class if any declaration is in a class */ function getTypeOfSpecialPropertyOfBaseType(specialProperty) { var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { @@ -33536,138 +34012,104 @@ var ts; } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - // Handle prototype property - if (symbol.flags & 4194304 /* Prototype */) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - // CommonsJS require and module both have type any. - if (symbol === requireSymbol || symbol === moduleSymbol) { - return links.type = anyType; - } - // Handle catch clause variables - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; - } - if (declaration.kind === 252 /* ExportAssignment */) { - return links.type = checkExpression(declaration.expression); - } - // Handle variable, parameter or property - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; - } - var type = getJSSpecialType(symbol, declaration); - if (!type) { - if (ts.isJSDocPropertyLikeTag(declaration) - || ts.isPropertyAccessExpression(declaration) - || ts.isIdentifier(declaration) - || ts.isClassDeclaration(declaration) - || ts.isFunctionDeclaration(declaration) - || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { - // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - return getTypeOfFuncClassEnumModule(symbol); - } - type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; - } - else if (ts.isPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); - } - else if (ts.isJsxAttribute(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); - } - else if (ts.isShorthandPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); - } - else if (ts.isObjectLiteralMethod(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); - } - else if (ts.isParameter(declaration) - || ts.isPropertyDeclaration(declaration) - || ts.isPropertySignature(declaration) - || ts.isVariableDeclaration(declaration) - || ts.isBindingElement(declaration)) { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); - } - else { - return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); - } - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); } - function getJSSpecialType(symbol, decl) { - if (!ts.isInJavaScriptFile(decl)) { - return undefined; + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } + if (declaration.kind === 252 /* ExportAssignment */) { + return checkExpression(declaration.expression); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJavaScriptFile(declaration) && + (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromJSPropertyAssignments(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } - else if (ts.isJSDocPropertyLikeTag(decl) && decl.typeExpression) { - return getTypeFromTypeNode(decl.typeExpression.type); - } - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - else if (ts.isBinaryExpression(decl) || - ts.isPropertyAccessExpression(decl) && ts.isBinaryExpression(decl.parent)) { - return getJSInitializerType(decl, symbol, ts.getAssignedJavascriptInitializer(ts.isBinaryExpression(decl) ? decl.left : decl)) || - getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else if (ts.isParameter(decl) - || ts.isPropertyDeclaration(decl) - || ts.isPropertySignature(decl) - || ts.isVariableDeclaration(decl) - || ts.isBindingElement(decl)) { - // Use type from type annotation if one is present - var isOptional = ts.isParameter(decl) && isJSDocOptionalParameter(decl) || - !ts.isBindingElement(decl) && !ts.isVariableDeclaration(decl) && !!decl.questionToken; - var declaredType = tryGetTypeFromEffectiveTypeNode(decl); - return declaredType && addOptionality(declaredType, isOptional) || - getJSInitializerType(decl, symbol, ts.getDeclaredJavascriptInitializer(decl)) || - getWidenedTypeForVariableLikeDeclaration(decl, /*includeOptionality*/ true); - } - } - function getJSInitializerType(decl, symbol, init) { - if (init && ts.isInJavaScriptFile(init) && ts.isObjectLiteralExpression(init)) { - var exports_1 = ts.createSymbolTable(); - while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { - var s_1 = getSymbolOfNode(decl); - if (s_1 && ts.hasEntries(s_1.exports)) { - mergeSymbolTable(exports_1, s_1.exports); - } - decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; - } - var s = getSymbolOfNode(decl); - if (s && ts.hasEntries(s.exports)) { - mergeSymbolTable(exports_1, s.exports); - } - return createAnonymousType(symbol, exports_1, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + return type; } - function getAnnotatedAccessorType(accessor) { + function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { if (accessor.kind === 156 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); - return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + return getterTypeAnnotation; } else { var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + return setterTypeAnnotation; } } return undefined; } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } function getAnnotatedAccessorThisParameter(accessor) { var parameter = getAccessorThisParameter(accessor); return parameter && parameter.symbol; @@ -33677,60 +34119,60 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; } - var type = void 0; - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; } else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); } + // Otherwise, fall back to 'any'. else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } - type = anyType; } + type = anyType; } } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); - } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } - links.type = type; } - return links.type; + return type; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -33738,6 +34180,7 @@ var ts; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); + var originalLinks = links; if (!links.type) { var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); if (jsDeclaration) { @@ -33756,32 +34199,45 @@ var ts; } } } - if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else if (symbol.valueDeclaration.kind === 202 /* BinaryExpression */ || - symbol.valueDeclaration.kind === 187 /* PropertyAccessExpression */ && symbol.valueDeclaration.parent.kind === 202 /* BinaryExpression */) { - links.type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - var type = createObjectType(16 /* Anonymous */, symbol); - if (symbol.flags & 32 /* Class */) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 202 /* BinaryExpression */ || + declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { + return getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; } - else { - links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); } + return type_1; } } - return links.type; + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } } function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); } function getTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); @@ -33807,7 +34263,7 @@ var ts; } else { if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type = errorType; } symbolInstantiationDepth++; var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); @@ -33911,8 +34367,8 @@ var ts; case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: case 240 /* TypeAliasDeclaration */: - case 300 /* JSDocTemplateTag */: - case 301 /* JSDocTypedefTag */: + case 301 /* JSDocTemplateTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: case 179 /* MappedType */: case 173 /* ConditionalType */: @@ -33975,15 +34431,18 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return false; + return isJavascriptConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + var isJavascript = ts.isInJavaScriptFile(location); + if (isJavascriptConstructorType(type) && !typeArgCount) { + return getSignaturesOfType(type, 0 /* Call */); + } + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); @@ -34070,6 +34529,9 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } + else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere @@ -34404,7 +34866,8 @@ var ts; } /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ function isThislessTypeParameter(node) { - return !node.constraint || isThislessType(node.constraint); + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); } /** * A variable-like declaration is free of this references if it has a type annotation @@ -34502,6 +34965,11 @@ var ts; && ts.isEntityNameExpression(node.expression) && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } /** * Indicates whether a declaration has a late-bindable dynamic name. */ @@ -34939,7 +35407,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_4 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -34962,7 +35430,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_4(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35066,7 +35534,7 @@ var ts; // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), /*_index*/ undefined, prop); + addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -35084,7 +35552,7 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - function addMemberForKeyType(t, _index, origin) { + function addMemberForKeyType(t) { // 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. @@ -35106,9 +35574,9 @@ var ts; prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : propType; - if (origin) { - prop.syntheticOrigin = origin; - prop.declarations = origin.declarations; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; } prop.nameType = t; members.set(propName, prop); @@ -35136,7 +35604,7 @@ var ts; errorType); } function getConstraintDeclarationForMappedType(type) { - return type.declaration.typeParameter.constraint; + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 @@ -35264,11 +35732,7 @@ var ts; return obj.properties.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - if (expected && typeIsLiteralType(expected)) { - var actual = getTypeOfNode(property); - return !!actual && !isTypeIdenticalTo(actual, expected); - } - return false; + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -35377,20 +35841,12 @@ var ts; } return undefined; } - function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { + function getBaseConstraintOfType(type) { if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - } - function getBaseConstraintOfType(type) { - var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); - if (!constraint && type.flags & 1048576 /* Index */) { - return keyofConstraintType; - } - return constraint; + return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35408,23 +35864,24 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var circular; - if (!type.resolvedBaseConstraint) { - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + var result = computeBaseConstraint(getSimplifiedType(t)); + if (!popTypeResolution()) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; } - return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { - circular = true; - return undefined; - } - var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { - circular = true; - return undefined; - } - return result; + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { if (t.flags & 65536 /* TypeParameter */) { @@ -35437,8 +35894,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_3 = types_4[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_4[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -35533,6 +35990,7 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; + var indexTypes; var isUnion = containingType.flags & 262144 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols @@ -35558,14 +36016,21 @@ var ts; } } else if (isUnion) { - checkFlags |= 16 /* Partial */; + var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); + if (index) { + checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, index.type); + } + else { + checkFlags |= 16 /* Partial */; + } } } } if (!props) { return undefined; } - if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } var declarations; @@ -35597,6 +36062,7 @@ var ts; } propTypes.push(type); } + ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && commonValueDeclaration) { @@ -35767,17 +36233,6 @@ var ts; var isBracketed = node.isBracketed, typeExpression = node.typeExpression; return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; } - function createTypePredicateFromTypePredicateNode(node) { - var parameterName = node.parameterName; - var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { - return createIdentifierTypePredicate(parameterName && parameterName.escapedText, // TODO: GH#18217 - parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); - } - else { - return createThisTypePredicate(type); - } - } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; } @@ -35853,7 +36308,7 @@ var ts; var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } - if (i === 0 && paramSymbol.escapedName === "this") { + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { hasThisParameter = true; thisParameter = param.symbol; } @@ -35887,9 +36342,9 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -35917,26 +36372,14 @@ var ts; parameters.push(syntheticArgsSymbol); return true; } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 - } - else if (classType) { - return classType; - } - var typeNode = ts.getEffectiveReturnTypeNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); - } - // TypeScript 1.0 spec (April 2014): - // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); } function containsArgumentsReference(declaration) { var links = getNodeLinks(declaration); @@ -36016,52 +36459,105 @@ var ts; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJavaScriptFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type) : - noTypePredicate; + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 71 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + type = anyType; } signature.resolvedReturnType = type; } return signature.resolvedReturnType; } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 155 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } function isResolvingReturnTypeOfSignature(signature) { return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */) || anyType; + return type && getIndexTypeOfType(type, 1 /* Number */); } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36161,7 +36657,7 @@ var ts; } function getConstraintDeclaration(type) { var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); - return decl && decl.constraint; + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { var inferences; @@ -36207,6 +36703,7 @@ var ts; } return inferences && getIntersectionType(inferences); } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { if (typeParameter.target) { @@ -36222,7 +36719,9 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */).parent); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); } function getTypeListId(types) { var result = ""; @@ -36412,6 +36911,10 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } + var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag && enumTag.typeExpression) { + return getTypeFromTypeNode(enumTag.typeExpression); + } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -36461,7 +36964,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 162 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -36552,7 +37055,7 @@ var ts; // The expression is processed as an identifier expression (section 4.3) // or property access expression(section 4.10), // the widened type(section 3.9) of which becomes the result. - links.resolvedType = getWidenedType(checkExpression(node.exprName)); + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); } return links.resolvedType; } @@ -36671,6 +37174,9 @@ var ts; function createArrayType(elementType) { return createTypeFromGenericGlobalType(globalArrayType, [elementType]); } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -36769,6 +37275,14 @@ var ts; function containsType(types, type) { return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } // Return true if the given intersection type contains // more than one unit type or, // an object type and a nullable type (null or undefined), or @@ -36932,7 +37446,7 @@ var ts; includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, includes & 16749629 /* NotUnit */ ? 0 : 67108864 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37047,29 +37561,65 @@ var ts; } } } - // When intersecting unions of unit types we can simply intersect based on type identity. - // Here we remove all unions of unit types from the given list and replace them with a - // a single union containing an intersection of the unit types. - function intersectUnionsOfUnitTypes(types) { - var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfUnitTypes */) !== 0; }); - var unionType = types[unionIndex]; - var intersection = unionType.types; - var i = types.length - 1; - var _loop_6 = function () { + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 64 /* StringLiteral */ ? stringType : + type.flags & 128 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfUnitTypes */) { - intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } - i--; - }; - while (i > unionIndex) { - _loop_6(); + else { + i++; + } } - if (intersection === unionType.types) { + // Return false if there was only one union of primitive types + if (!unionTypes) { return false; } - types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 67108864 /* UnionOfUnitTypes */); + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -37109,7 +37659,7 @@ var ts; return typeSet[0]; } if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -37220,6 +37770,33 @@ var ts; type.indexType = indexType; return type; } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 262144 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 524288 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 15794176 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : @@ -37239,7 +37816,8 @@ var ts; getNodeLinks(accessNode).resolvedSymbol = prop; } } - return getTypeOfSymbol(prop); + var propType = getTypeOfSymbol(prop); + return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; } if (isTupleType(objectType)) { var restType = getRestTypeOfTupleType(objectType); @@ -37249,7 +37827,7 @@ var ts; } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (isTypeAny(objectType)) { + if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { return objectType; } var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || @@ -37268,9 +37846,15 @@ var ts; if (indexType.flags & 32768 /* Never */) { return neverType; } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1 /* Number */)) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); } else { @@ -37288,6 +37872,9 @@ var ts; return anyType; } } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessNode) { var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { @@ -37374,7 +37961,7 @@ var ts; return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 65536 /* TypeParameter */) { - var constraint = getConstraintFromTypeParameter(objectType); + var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); } @@ -37601,19 +38188,17 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var argumentType = getTypeFromTypeNode(node.argument); - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type - var moduleName = argumentType.value; - var innerModuleSymbol = resolveExternalModule(node, moduleName, ts.Diagnostics.Cannot_find_module_0, node, /*isForAugmentation*/ false); + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var moduleSymbol_1 = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); - var currentNamespace = moduleSymbol_1; + var currentNamespace = moduleSymbol; var current = void 0; while (current = nameStack.shift()) { var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; @@ -37629,14 +38214,14 @@ var ts; resolveImportSymbolType(node, links, currentNamespace, targetMeaning); } else { - if (moduleSymbol_1.flags & targetMeaning) { - resolveImportSymbolType(node, links, moduleSymbol_1, targetMeaning); + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { var errorMessage = targetMeaning === 67216319 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; - error(node, errorMessage, moduleName); + error(node, errorMessage, node.argument.literal.text); links.resolvedSymbol = unknownSymbol; links.resolvedType = errorType; } @@ -37722,20 +38307,16 @@ var ts; } for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; - // we approximate own properties as non-methods plus methods that are inside the object literal - var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.escapedName, true); } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + else if (isSpreadableProperty(rightProp)) { members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { var leftProp = _c[_b]; - if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) - || skippedPrivateMembers.has(leftProp.escapedName) - || isClassMethod(leftProp)) { + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { continue; } if (members.has(leftProp.escapedName)) { @@ -37762,6 +38343,12 @@ var ts; spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) + ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) + : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { return prop; @@ -37780,9 +38367,6 @@ var ts; } return index; } - function isClassMethod(prop) { - return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } function createLiteralType(flags, value, symbol) { var type = createType(flags); type.symbol = symbol; @@ -37942,7 +38526,7 @@ var ts; case 71 /* Identifier */: case 146 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: return errorType; } @@ -38118,7 +38702,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavaScriptConstructor(declaration_1)) { + if (isJavascriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38178,11 +38762,16 @@ var ts; } } 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 - // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated - // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for - // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a - // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & 1048576 /* Index */) { var typeVariable_1 = constraintType.type; @@ -38191,7 +38780,11 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); + var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); } return t; }); @@ -38203,6 +38796,25 @@ var ts; function isMappableType(type) { return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + propType; + } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { @@ -38354,6 +38966,9 @@ var ts; return true; } } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); @@ -38365,7 +38980,7 @@ var ts; function getTypeWithoutSignatures(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { + if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; @@ -38505,8 +39120,8 @@ var ts; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } - if (!issuedElaboration && (ts.length(targetProp && targetProp.declarations) || ts.length(target.symbol && target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); } } reportedError = true; @@ -38655,9 +39270,9 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceRestTypeParameter = getRestTypeParameter(source); - var targetRestTypeParameter = sourceRestTypeParameter ? getRestTypeParameter(target) : undefined; - if (sourceRestTypeParameter && !(targetRestTypeParameter && sourceCount === targetCount)) { + var sourceGenericRestType = getGenericRestType(source); + var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; + if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -38683,8 +39298,8 @@ var ts; var paramCount = Math.max(sourceCount, targetCount); var lastIndex = paramCount - 1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceRestTypeParameter || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetRestTypeParameter || getTypeAtPosition(target, i); + var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); + var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -38710,11 +39325,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? + getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? + getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39219,6 +39836,9 @@ var ts; return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && @@ -39229,7 +39849,7 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_7 = function (prop) { + var _loop_5 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -39268,9 +39888,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_7(prop); - if (typeof state_3 === "object") - return state_3.value; + var state_2 = _loop_5(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -39302,7 +39922,8 @@ var ts; } if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || - findMatchingTypeReferenceOrTypeAliasReference(source, target); + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39324,6 +39945,11 @@ var ts; }); } } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -39923,8 +40549,12 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); + var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { // An abstract constructor type is not assignable to a non-abstract constructor type @@ -40174,7 +40804,7 @@ var ts; return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -40436,6 +41066,9 @@ var ts; function isArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray @@ -40618,7 +41251,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; - regularNew.objectFlags |= 128 /* ObjectLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; } @@ -40696,7 +41329,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); - return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); @@ -40828,13 +41463,13 @@ var ts; sourceHasRest ? targetCount : targetHasRest ? sourceCount : Math.min(sourceCount, targetCount); - var targetRestTypeVariable = getRestTypeParameter(target); - var paramCount = targetRestTypeVariable ? Math.min(targetCount - 1, maxCount) : maxCount; + var targetGenericRestType = getGenericRestType(target); + var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetRestTypeVariable) { - callback(getRestTypeAtPosition(source, paramCount), targetRestTypeVariable); + if (targetGenericRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -40946,6 +41581,22 @@ var ts; return undefined; } } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; @@ -41510,7 +42161,7 @@ var ts; case 71 /* Identifier */: return ts.idText(name); case 147 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; @@ -41534,8 +42185,9 @@ var ts; case 97 /* SuperKeyword */: return target.kind === 97 /* SuperKeyword */; case 187 /* PropertyAccessExpression */: - return target.kind === 187 /* PropertyAccessExpression */ && - source.name.escapedText === target.name.escapedText && + case 188 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); case 184 /* BindingElement */: if (target.kind !== 187 /* PropertyAccessExpression */) @@ -41553,6 +42205,11 @@ var ts; } return false; } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } function containsMatchingReference(source, target) { while (source.kind === 187 /* PropertyAccessExpression */) { source = source.expression; @@ -41632,18 +42289,6 @@ var ts; } return flow.id; } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 262144 /* Union */)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -41652,7 +42297,7 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); if (!(reducedType.flags & 32768 /* Never */)) { return reducedType; } @@ -41908,7 +42553,7 @@ var ts; if (type.flags & 262144 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfUnitTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); } return f(type) ? type : neverType; } @@ -42150,7 +42795,10 @@ var ts; 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 !== 187 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + if (container && container !== flowContainer && + reference.kind !== 187 /* PropertyAccessExpression */ && + reference.kind !== 188 /* ElementAccessExpression */ && + reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -42379,13 +43027,22 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 187 /* PropertyAccessExpression */ && - computedType.flags & 262144 /* Union */ && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(computedType, expr.name.escapedText); + if (!(computedType.flags & 262144 /* Union */) || + expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.escapedText; + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); @@ -42669,6 +43326,7 @@ var ts; case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); case 189 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); @@ -42885,6 +43543,7 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -42896,7 +43555,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || node.parent.kind === 211 /* NonNullExpression */ || @@ -43059,15 +43718,14 @@ var ts; // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); - var needToCaptureLexicalThis = false; + var capturedByArrowFunction = false; if (container.kind === 155 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. if (container.kind === 195 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); - // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); + capturedByArrowFunction = true; } switch (container.kind) { case 242 /* ModuleDeclaration */: @@ -43095,13 +43753,16 @@ var ts; error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } - if (needToCaptureLexicalThis) { + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { captureLexicalThis(node, container); } var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); } return type || anyType; } @@ -43110,8 +43771,8 @@ var ts; if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. Check if it's the RHS - // of a x.prototype.y = function [name]() { .... } + // If this is a function in a JS file, it might be a class method. + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } if (container.kind === 194 /* FunctionExpression */ && container.parent.kind === 202 /* BinaryExpression */ && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { @@ -43125,6 +43786,17 @@ var ts; return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); } } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJavascriptClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return getFlowTypeOfReference(node, thisType); @@ -43148,7 +43820,7 @@ var ts; var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && - jsDocFunctionType.parameters[0].name.escapedText === "this") { + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } @@ -43437,20 +44109,10 @@ var ts; } var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameter = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameter ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - // If last parameter is contextually rest parameter get its type - if (funcHasRestParameter && indexOfParameter === len) { - return getRestTypeAtPosition(contextualSignature, indexOfParameter); - } + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); } } // In a variable, parameter or property declaration with a type annotation, @@ -43536,10 +44198,9 @@ var ts; function getContextualReturnType(functionDecl) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.kind === 155 /* Constructor */ || - ts.getEffectiveReturnTypeNode(functionDecl) || - isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature @@ -43588,22 +44249,39 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments to avoid circularity. + // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function isContextSensitiveAssignment(binaryExpression) { var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); switch (kind) { case 0 /* None */: return true; case 5 /* Property */: - // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. - // See `bindStaticPropertyAssignment` in `binder.ts`. - return !binaryExpression.left.symbol; case 1 /* ExportsProperty */: - case 2 /* ModuleExports */: + case 6 /* Prototype */: case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + if (ts.isInJavaScriptFile(decl)) { + return !!ts.getJSDocTypeTag(decl); + } + else if (ts.isIdentifier(binaryExpression.left.expression)) { + var id = binaryExpression.left.expression; + var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); + return !ts.isFunctionSymbol(parentSymbol); + } + return true; + } case 4 /* ThisProperty */: - case 6 /* Prototype */: - return false; + case 2 /* ModuleExports */: + return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); default: return ts.Debug.assertNever(kind); } @@ -44018,16 +44696,11 @@ var ts; // union type of return types from these signatures function getContextualSignature(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type; - if (ts.isInJavaScriptFile(node)) { - var jsdoc = ts.getJSDocType(node); - if (jsdoc) { - type = getTypeFromTypeNode(jsdoc); - } - } - if (!type) { - type = getContextualTypeForFunctionLikeDeclaration(node); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; } + var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } @@ -44235,7 +44908,8 @@ var ts; var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); - var isJSObjectLiteral = !contextualType && isInJSFile; + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44259,6 +44933,9 @@ var ts; checkTypeAssignableTo(type, jsDocType, memberDecl); type = jsDocType; } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } } typeFlags |= type.flags; var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? @@ -44368,12 +45045,15 @@ var ts; } return createObjectLiteralType(); function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); result.objectFlags |= 128 /* ObjectLiteral */; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } @@ -44760,7 +45440,7 @@ var ts; var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); @@ -44796,7 +45476,7 @@ var ts; if (jsxStatelessElementType) { // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); var result = void 0; var allMatchingAttributesType = void 0; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { @@ -45104,6 +45784,10 @@ var ts; } } } + else if (targetType.flags & 4194304 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } return false; } /** @@ -45161,11 +45845,6 @@ var ts; return errorType; } } - // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized - // '.prototype' property as well as synthesized tuple index properties. - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 152 /* PropertyDeclaration */; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } @@ -45187,23 +45866,19 @@ var ts; * Check whether the requested property access is valid. * Returns true if node is a valid property access, and false otherwise. * @param node The node to be checked. - * @param left The left hand side of the property access (e.g.: the super in `super.foo`). - * @param type The type of left. - * @param prop The symbol for the right hand side of the property access. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, left, type, prop) { + function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 187 /* PropertyAccessExpression */ || node.kind === 235 /* VariableDeclaration */ ? - node.name : - node.kind === 181 /* ImportType */ ? - node : - node.right; + var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or // instance member variable initializer where this references a derived class instance, @@ -45250,7 +45925,7 @@ var ts; } // Property is known to be protected at this point // All protected properties of a supertype are accessible in a super access - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { return true; } // Find the first enclosing class that has the declaring classes of the protected constituents @@ -45269,7 +45944,7 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintFromTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { @@ -45290,10 +45965,7 @@ var ts; return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; } function symbolHasNonMethodDeclaration(symbol) { - return forEachProperty(symbol, function (prop) { - var propKind = getDeclarationKindFromSymbol(prop); - return propKind !== 154 /* MethodDeclaration */ && propKind !== 153 /* MethodSignature */; - }); + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); @@ -45339,6 +46011,9 @@ var ts; if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } @@ -45353,7 +46028,7 @@ var ts; checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); @@ -45411,7 +46086,7 @@ var ts; diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializer(node) { @@ -45456,6 +46131,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; + var relatedInfo; if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; @@ -45465,32 +46141,44 @@ var ts; } } } - var promisedType = getPromisedTypeOfPromise(containingType); - if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - 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), suggestion); + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion_1 = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion_1 !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion_1); + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { - var suggestion = getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); @@ -45500,10 +46188,17 @@ var ts; // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - return result && ts.symbolName(result); + return result; + } + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); } - function getSuggestionForNonexistentModule(name, targetModule) { - var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); return suggestion && ts.symbolName(suggestion); } /** @@ -45547,15 +46242,15 @@ var ts; function isValidPropertyAccess(node, propertyName) { switch (node.kind) { case 187 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression, propertyName, getWidenedType(checkExpression(node.expression))); + return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); case 146 /* QualifiedName */: - return isValidPropertyAccessWithType(node, node.left, propertyName, getWidenedType(checkExpression(node.left))); + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); case 181 /* ImportType */: - return isValidPropertyAccessWithType(node, node, propertyName, getTypeFromTypeNode(node)); + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 181 /* ImportType */ ? node : node.expression, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -45575,14 +46270,14 @@ var ts; inferTypes(context.inferences, actualThisType, signatureThisType); return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); } - function isValidPropertyAccessWithType(node, left, propertyName, type) { + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { if (type === errorType || isTypeAny(type)) { return true; } var prop = getPropertyOfType(type, propertyName); - return prop ? checkPropertyAccessibility(node, left, type, prop) + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -45778,7 +46473,6 @@ var ts; function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call - var typeArguments; // Type arguments (undefined if none) var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { @@ -45789,7 +46483,6 @@ var ts; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = node.typeArguments; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. @@ -45806,7 +46499,6 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { @@ -45818,12 +46510,8 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } - if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { - return false; - } // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. if (spreadArgIndex >= 0) { return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); @@ -45927,8 +46615,8 @@ var ts; // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var restTypeParameter = getRestTypeParameter(signature); - var argCount = restTypeParameter ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var genericRestType = getGenericRestType(signature); + var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. @@ -45946,9 +46634,9 @@ var ts; inferTypes(context.inferences, argType, paramType); } } - if (restTypeParameter) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, restTypeParameter, context); - inferTypes(context.inferences, spreadType, restTypeParameter); + if (genericRestType) { + var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); + inferTypes(context.inferences, spreadType, genericRestType); } // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed @@ -46344,7 +47032,7 @@ var ts; node.kind === 157 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - var propertyType = getTypeOfNode(node); // TODO: GH#18217 + var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); @@ -46410,18 +47098,54 @@ var ts; return arg; } } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + min = Math.min(min, minCount); + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } var paramCount = min === max ? min : min + "-" + max; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; var isDecorator = node.kind === 150 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -46493,11 +47217,12 @@ var ts; // foo(0); // var candidateForArgumentError; + var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -46533,73 +47258,30 @@ var ts; // an error, we don't need to exclude any arguments, although it would cause no harm to do so. checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { - var min_1 = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; - min_1 = Math.min(min_1, getMinArgumentCount(sig)); - max = Math.max(max, getParameterCount(sig)); - } - var hasRestParameter_1 = ts.some(signatures, hasEffectiveRestParameter); - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - var paramCount = hasRestParameter_1 ? min_1 : - min_1 < max ? min_1 + "-" + max : - min_1; - var argCount = args.length; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - ts.Diagnostics.Expected_0_arguments_but_got_1; - diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + diagnostics.add(getArgumentArityError(node, signatures, args)); } else if (fallbackError) { diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } - // No signature was applicable. We have already reported the errors for the invalid signature. - // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. - // Pick the longest signature. This way we can get a contextual type for cases like: - // declare function f(a: { xa: number; xb: number; }, b: number); - // f({ | - // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: - // declare function f(k: keyof T); - // f(" - if (!produceDiagnostics) { - ts.Debug.assert(candidates.length > 0); // Else would have exited above. - var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); - var candidate = candidates[bestIndex]; - var typeParameters = candidate.typeParameters; - if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); // TODO: GH#18217 - while (typeArguments_1.length > typeParameters.length) { - typeArguments_1.pop(); - } - while (typeArguments_1.length < typeParameters.length) { - typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); - } - var instantiated = createSignatureInstantiation(candidate, typeArguments_1); - candidates[bestIndex] = instantiated; - return instantiated; - } - return candidate; - } - return resolveErrorCall(node); + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -46610,7 +47292,7 @@ var ts; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; @@ -46636,6 +47318,12 @@ var ts; } var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = candidate; + break; + } } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; @@ -46657,6 +47345,87 @@ var ts; return undefined; } } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_6 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_6(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments); + candidates[bestIndex] = instantiated; + return instantiated; + } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; var maxParams = -1; @@ -46673,11 +47442,14 @@ var ts; } return maxParamsIndex; } - function resolveCallExpression(node, candidatesOutArray) { + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { - ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } return anySignature; } if (superType !== errorType) { @@ -46686,7 +47458,7 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); } } return resolveUntypedCall(node); @@ -46729,7 +47501,12 @@ var ts; } return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * TS 1.0 spec: 4.12 @@ -46741,7 +47518,7 @@ var ts; return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } - function resolveNewExpression(node, candidatesOutArray) { + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { @@ -46789,7 +47566,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray); + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -46797,8 +47574,8 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } if (getThisTypeOfSignature(signature) === voidType) { @@ -46809,6 +47586,38 @@ var ts; invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 524288 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } function isConstructorAccessible(node, signature) { if (!signature || !signature.declaration) { return true; @@ -46824,16 +47633,10 @@ var ts; // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); - if (containingClass) { + if (containingClass && modifiers & 16 /* Protected */) { var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; } } if (modifiers & 8 /* Private */) { @@ -46865,7 +47668,7 @@ var ts; addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); if (apparentType === errorType) { @@ -46881,7 +47684,7 @@ var ts; invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -46906,7 +47709,7 @@ var ts; /** * Resolves a decorator as if it were a call expression. */ - function resolveDecorator(node, candidatesOutArray) { + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); if (apparentType === errorType) { @@ -46931,7 +47734,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -46955,30 +47758,30 @@ var ts; * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; * the function will fill it up with appropriate candidate signatures */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); } return undefined; } - function resolveSignature(node, candidatesOutArray) { + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { case 189 /* CallExpression */: - return resolveCallExpression(node, candidatesOutArray); + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); case 190 /* NewExpression */: - return resolveNewExpression(node, candidatesOutArray); + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); case 191 /* TaggedTemplateExpression */: - return resolveTaggedTemplateExpression(node, candidatesOutArray); + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); case 150 /* Decorator */: - return resolveDecorator(node, candidatesOutArray); + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); case 260 /* JsxOpeningElement */: case 259 /* JsxSelfClosingElement */: // This code-path is called by language service var exprTypes = checkExpression(node.tagName); return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); if (sfcResult && sfcResult !== unknownSignature) { return sfcResult; } @@ -46998,7 +47801,8 @@ var ts; * the function will fill it up with appropriate candidate signatures * @return a signature of the call-like expression or undefined if one can't be found */ - function getResolvedSignature(node, candidatesOutArray) { + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } var links = getNodeLinks(node); // If getResolvedSignature has already been called, we will have cached the resolvedSignature. // However, it is possible that either candidatesOutArray was not passed in the first time, @@ -47009,7 +47813,7 @@ var ts; return cached; } links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); // If signature resolution originated in control flow type analysis (for example to compute the // assigned type in a flow assignment) we don't cache the result as it may be based on temporary // types from the control flow analysis. @@ -47020,7 +47824,7 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavaScriptConstructor(node) { + function isJavascriptConstructor(node) { if (node && ts.isInJavaScriptFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) @@ -47033,14 +47837,21 @@ var ts; } return false; } - function getJavaScriptClassType(symbol) { + function isJavascriptConstructorType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJavascriptClassType(symbol) { var inferred; - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47113,7 +47924,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavaScriptClassType(funcSymbol); + var type = funcSymbol && getJavascriptClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47139,7 +47950,8 @@ var ts; if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { - jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; } } } @@ -47256,7 +48068,7 @@ var ts; if (produceDiagnostics && targetType !== errorType) { var widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); } } return targetType; @@ -47323,6 +48135,9 @@ var ts; return restParameter.escapedName; } function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); @@ -47333,22 +48148,19 @@ var ts; if (pos - paramCount < getLengthOfTupleType(restType)) { return restType.typeArguments[pos - paramCount]; } - var tupleRestType = getRestTypeOfTupleType(restType); - if (tupleRestType) { - return tupleRestType; - } + return getRestTypeOfTupleType(restType); } - return getIndexTypeOfType(restType, 1 /* Number */) || anyType; + return getIndexTypeOfType(restType, 1 /* Number */); } - return anyType; + return undefined; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); var hasRest = hasEffectiveRestParameter(source); if (hasRest && pos === paramCount - 1) { - var restTypeVariable = getRestTypeParameter(source); - if (restTypeVariable) { - return restTypeVariable; + var genericRestType = getGenericRestType(source); + if (genericRestType) { + return genericRestType; } } var start = hasRest ? Math.min(pos, paramCount - 1) : pos; @@ -47394,10 +48206,10 @@ var ts; } return signature.minArgumentCount; } - function getRestTypeParameter(signature) { + function getGenericRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 65536 /* TypeParameter */) { + if (restType.flags & 15794176 /* Instantiable */) { return restType; } } @@ -47665,7 +48477,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -47696,7 +48508,7 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 3 /* AnyOrUnknown */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. @@ -47737,6 +48549,16 @@ var ts; ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + } return anyFunctionType; } // Grammar checking @@ -47768,7 +48590,7 @@ var ts; contextualSignature : instantiateSignature(contextualSignature, contextualMapper); assignContextualParameterTypes(signature, instantiatedContextualSignature); } - if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, checkMode); if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; @@ -47781,20 +48603,21 @@ var ts; } return type; } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - var returnOrPromisedType = returnTypeNode && - ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : // Async function - getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { - if (!returnTypeNode) { + if (!ts.getEffectiveReturnTypeNode(node)) { // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors // we need. An example is the noImplicitAny errors resulting from widening the return expression // of a function. Because checking of function expression bodies is deferred, there was never an @@ -47858,7 +48681,7 @@ var ts; // If func.parent is a class and symbol is a (readonly) property of that class, or // if func is a constructor and symbol is a (readonly) parameter property declared in it, // then symbol is writeable here. - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -47944,6 +48767,7 @@ var ts; } return numberType; case 51 /* ExclamationToken */: + checkTruthinessExpression(node.operand); var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); return facts === 1048576 /* Truthy */ ? falseType : facts === 2097152 /* Falsy */ ? trueType : @@ -48053,19 +48877,20 @@ var ts; } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType) { + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { var properties = node.properties; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; } /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { var name = property.name; if (name.kind === 147 /* ComputedPropertyName */) { @@ -48074,20 +48899,10 @@ var ts; if (isComputedNonLiteralName(name)) { return undefined; } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || - getIndexTypeOfType(objectLiteralType, 0 /* String */); + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { - if (property.kind === 274 /* ShorthandPropertyAssignment */) { - return checkDestructuringAssignment(property, type); - } - else { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.initializer, type); - } + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); @@ -48111,6 +48926,23 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -48168,7 +49000,7 @@ var ts; } return undefined; } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; @@ -48191,7 +49023,7 @@ var ts; target = target.left; } if (target.kind === 186 /* ObjectLiteralExpression */) { - return checkObjectLiteralAssignment(target, sourceType); + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } if (target.kind === 185 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); @@ -48281,9 +49113,15 @@ var ts; function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + } + var leftType; + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); } - var leftType = checkExpression(left, checkMode); var rightType = checkExpression(right, checkMode); switch (operator) { case 39 /* AsteriskToken */: @@ -48405,7 +49243,7 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.getSpecialPropertyAssignmentKind(left.parent); + var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; checkSpecialAssignment(special, right); if (isJSSpecialPropertyAssignment(special)) { return leftType; @@ -48485,8 +49323,9 @@ var ts; } function isJSSpecialPropertyAssignment(special) { switch (special) { - case 1 /* ExportsProperty */: case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: case 5 /* Property */: case 6 /* Prototype */: case 3 /* PrototypeProperty */: @@ -48570,16 +49409,16 @@ var ts; // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. - var returnType = ts.getEffectiveReturnTypeNode(func); + var returnType = getReturnTypeFromAnnotation(func); if (returnType) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); } // Both yield and yield* expressions have type 'any' return anyType; } function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); + checkTruthinessExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -48592,7 +49431,7 @@ var ts; // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { - error(templateSpan.expression, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1, typeToString(esSymbolType), typeToString(stringType)); + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; @@ -48762,9 +49601,6 @@ var ts; node.contextualType = saveContextualType; return type; } - function checkExpresionNoReturn(node) { - checkExpression(node); - } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -48907,7 +49743,7 @@ var ts; checkSourceElement(node.default); var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } if (!hasNonCircularTypeParameterDefault(typeParameter)) { error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); @@ -48947,6 +49783,9 @@ var ts; if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } + if (func.kind === 195 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. @@ -48954,17 +49793,6 @@ var ts; error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - } - return -1; - } function checkTypePredicate(node) { var parent = getTypePredicateParent(node); if (!parent) { @@ -48988,8 +49816,7 @@ var ts; } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), // TODO: GH#18217 - node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -49110,7 +49937,7 @@ var ts; } } else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node); + checkAsyncFunctionReturnType(node, returnTypeNode); } } if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { @@ -49565,7 +50392,10 @@ var ts; } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, keyofConstraintType, node.typeParameter.constraint); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); } function checkTypeOperator(node) { checkGrammarTypeOperatorNode(node); @@ -49579,6 +50409,7 @@ var ts; grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); } function checkImportType(node) { checkSourceElement(node.argument); @@ -49866,7 +50697,7 @@ var ts; case 239 /* InterfaceDeclaration */: case 240 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return 2 /* ExportType */; case 242 /* ModuleDeclaration */: @@ -50065,16 +50896,15 @@ var ts; * Checks the return type of an async function to ensure it is a compatible * Promise implementation. * - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. * * @param node The signature to check */ - function checkAsyncFunctionReturnType(node) { + function checkAsyncFunctionReturnType(node, returnTypeNode) { // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -50099,30 +50929,29 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); // TODO: GH#18217 var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (returnType === errorType) { - return errorType; + return; } var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return errorType; + return; } } else { // Always mark the type node as referenced if it points to a value markTypeNodeAsReferenced(returnTypeNode); if (returnType === errorType) { - return errorType; + return; } var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === undefined) { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return errorType; + return; } var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; @@ -50133,28 +50962,27 @@ var ts; else { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); } - return errorType; + return; } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return errorType; + return; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } } - // Get and return the awaited type of the return type. - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } /** Check a decorator */ function checkDecorator(node) { @@ -50185,7 +51013,7 @@ var ts; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); // TODO: GH#18217 + var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; @@ -50309,9 +51137,13 @@ var ts; } } break; - case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: + var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 154 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); @@ -50351,6 +51183,13 @@ var ts; } checkSourceElement(node.typeExpression); } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } @@ -50445,14 +51284,11 @@ var ts; } var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function - var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ - ? checkAsyncFunctionReturnType(node) // Async function - : getTypeFromTypeNode(returnTypeNode)); // normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } - if (produceDiagnostics && !returnTypeNode) { + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { @@ -50465,6 +51301,13 @@ var ts; getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJavaScriptFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. @@ -50519,6 +51362,7 @@ var ts; case 163 /* FunctionType */: case 164 /* ConstructorType */: case 240 /* TypeAliasDeclaration */: + case 174 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -50529,7 +51373,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; @@ -50549,14 +51393,14 @@ var ts; } var symbol = getSymbolOfNode(member); if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; case 155 /* 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 */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } } break; @@ -50573,16 +51417,45 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { + if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + return; + if (node.kind === 174 /* InferType */) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + else { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; - if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol))); + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } function addToGroup(map, key, value, getKey) { var keyString = String(getKey(key)); var group = map.get(keyString); @@ -50633,7 +51506,7 @@ var ts; var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); if (parameter && name) { if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { @@ -50650,7 +51523,7 @@ var ts; (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { - addDiagnostic(0 /* Local */, unuseds.length === 1 + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); } @@ -50669,29 +51542,29 @@ var ts; addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - addDiagnostic(kind, bindingElements.length === 1 - ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); } } else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; - addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); } } }); unusedVariables.forEach(function (_a) { var declarationList = _a[0], declarations = _a[1]; if (declarationList.declarations.length === declarations.length) { - addDiagnostic(0 /* Local */, declarations.length === 1 + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var decl = declarations_5[_i]; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); } } }); @@ -50994,10 +51867,13 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + } } } } @@ -51118,7 +51994,7 @@ var ts; function checkIfStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); if (node.thenStatement.kind === 218 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); @@ -51129,14 +52005,21 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); checkSourceElement(node.statement); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); } function checkWhileStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.statement); } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 4096 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { @@ -51153,7 +52036,7 @@ var ts; } } if (node.condition) - checkExpression(node.condition); + checkTruthinessExpression(node.condition); if (node.incrementor) checkExpression(node.incrementor); checkSourceElement(node.statement); @@ -51557,10 +52440,6 @@ var ts; checkGrammarBreakOrContinueStatement(node); // TODO: Check that target label is valid } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 156 /* GetAccessor */ - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 157 /* SetAccessor */)) !== undefined; - } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function @@ -51600,7 +52479,7 @@ var ts; error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + else if (getReturnTypeFromAnnotation(func)) { if (functionFlags & 2 /* Async */) { // Async function var promisedType = getPromisedTypeOfPromise(returnType); var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -51909,8 +52788,9 @@ var ts; } // If the type parameter node does not have an identical constraint as the resolved // type parameter at this position, we report an error. - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); if (sourceConstraint) { // relax check if later interface augmentation has no constraint if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { @@ -52006,8 +52886,9 @@ var ts; // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52050,7 +52931,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_7 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52069,7 +52950,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_7(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -52829,9 +53710,9 @@ var ts; } else { // export * from "foo" - var moduleSymbol_2 = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol_2 && hasExportAssignmentSymbol(moduleSymbol_2)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol_2)); + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + 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 && moduleKind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768 /* ExportStar */); @@ -52922,9 +53803,9 @@ var ts; } } // Checks for export * conflicts - var exports_2 = getExportsOfModule(moduleSymbol); - if (exports_2) { - exports_2.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -53024,6 +53905,8 @@ var ts; case 169 /* OptionalType */: case 170 /* RestType */: return checkSourceElement(node.type); + case 176 /* ThisType */: + return checkThisType(node); case 177 /* TypeOperator */: return checkTypeOperator(node); case 173 /* ConditionalType */: @@ -53034,12 +53917,14 @@ var ts; return checkImportType(node); case 293 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 299 /* JSDocTypeTag */: + case 301 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 300 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: return checkJSDocParameterTag(node); case 287 /* JSDocFunctionType */: checkSignatureDeclaration(node); @@ -53252,10 +54137,7 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1 /* TypeChecked */)) { - // If skipLibCheck is enabled, skip type checking if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip type checking if file contains a - // '/// ' directive. - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + if (ts.skipTypeChecking(node, compilerOptions)) { return; } // Grammar checking @@ -53269,8 +54151,8 @@ var ts; registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { - if (unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { diagnostics.add(diag); } }); @@ -53349,6 +54231,7 @@ var ts; var symbols = ts.createSymbolTable(); var isStatic = false; populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword return symbolsToArray(symbols); function populateSymbols() { while (location) { @@ -53571,10 +54454,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 296 /* JSDocParameterTag */) { + if (entityName.parent.kind === 297 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 300 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -53643,7 +54526,7 @@ var ts; grandParent.kind === 182 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; } @@ -53727,7 +54610,7 @@ var ts; } if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { var containingClass = ts.getContainingClass(node); var classType = getTypeOfNode(containingClass); typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); @@ -53742,8 +54625,8 @@ var ts; // extends clause of a class. We handle that case here. var classNode = ts.getContainingClass(node); var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -53752,7 +54635,7 @@ var ts; } if (isTypeDeclarationName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } if (ts.isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -53761,10 +54644,10 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); + return symbol ? getTypeOfSymbol(symbol) : errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -54382,7 +55265,8 @@ var ts; setAccessor: setAccessor, getAccessor: getAccessor }; - } + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55493,9 +56377,6 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - if (node.name.kind === 183 /* ArrayBindingPattern */ || node.name.kind === 182 /* ObjectBindingPattern */) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (node.propertyName) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); } @@ -55767,10 +56648,10 @@ var ts; // this has already been reported, and don't report if it has. // if (node.parent.kind === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { - var links_1 = getNodeLinks(node.parent); + var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); } } else { @@ -56902,19 +57783,7 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - 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; - } + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters @@ -57026,17 +57895,7 @@ var ts; return node; } ts.createConditional = createConditional; - 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]; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue @@ -57839,7 +58698,7 @@ var ts; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -57855,7 +58714,7 @@ var ts; function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(260 /* JsxOpeningElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -58150,7 +59009,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(304 /* NotEmittedStatement */); + var node = createSynthesizedNode(305 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -58162,7 +59021,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(308 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -58174,7 +59033,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(307 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -58189,7 +59048,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(305 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -58205,7 +59064,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 306 /* CommaListExpression */) { + if (node.kind === 307 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -58215,7 +59074,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(306 /* CommaListExpression */); + var node = createSynthesizedNode(307 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -59385,6 +60244,11 @@ var ts; var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1 /* LessThan */: @@ -59527,11 +60391,15 @@ var ts; */ function parenthesizeDefaultExpression(e) { var check = ts.skipPartiallyEmittedExpressions(e); - return check.kind === 207 /* ClassExpression */ || - check.kind === 194 /* FunctionExpression */ || - isCommaSequence(check) - ? ts.createParen(e) - : e; + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; } ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; /** @@ -59684,6 +60552,9 @@ var ts; case 203 /* ConditionalExpression */: node = node.condition; continue; + case 191 /* TaggedTemplateExpression */: + node = node.tag; + continue; case 189 /* CallExpression */: if (stopAtCallExpressions) { return node; @@ -59693,7 +60564,7 @@ var ts; case 188 /* ElementAccessExpression */: case 187 /* PropertyAccessExpression */: case 211 /* NonNullExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -59709,7 +60580,7 @@ var ts; ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || - node.kind === 306 /* CommaListExpression */; + node.kind === 307 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -59728,7 +60599,7 @@ var ts; case 210 /* AsExpression */: case 211 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -59765,7 +60636,7 @@ var ts; case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 305 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -60042,7 +60913,7 @@ var ts; // `1` in `let { 1: b } = ...` if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -60054,7 +60925,7 @@ var ts; // `1` in `({ 1: b } = ...)` if (bindingElement.name) { var propertyName = bindingElement.name; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -60065,13 +60936,18 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) ? target.expression : target; } ts.Debug.fail("Invalid property name for binding element."); } ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } /** * Gets the elements of a BindingOrAssignmentPattern */ @@ -60555,9 +61431,9 @@ var ts; case 277 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -60613,7 +61489,7 @@ var ts; case 218 /* EmptyStatement */: case 208 /* OmittedExpression */: case 234 /* DebuggerStatement */: - case 304 /* NotEmittedStatement */: + case 305 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -60992,10 +61868,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -61009,8 +61885,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) - : ts.prependStatements(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -61188,7 +62064,7 @@ var ts; function decode(host, mapPath, map, program, fallbackCache) { if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot || currentDirectory; + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; var decodedMappings; var generatedOrderedMappings; var sourceOrderedMappings; @@ -61223,10 +62099,11 @@ var ts; } function getSourceFileLike(fileName, location) { // Lookup file in program, if provided - var file = program && program.getSourceFile(fileName); - if (!file) { + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + var file = program && program.getSourceFile(path); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (!file || file.resolvedPath !== path) { // Otherwise check the cache (which may hit disk) - var path = ts.toPath(fileName, location, host.getCanonicalFileName); return fallbackCache.get(path); } return file; @@ -62062,7 +62939,7 @@ var ts; var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); return ts.createElementAccess(value, argumentExpression); } - else if (ts.isStringOrNumericLiteral(propertyName)) { + else if (ts.isStringOrNumericLiteralLike(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); @@ -62742,7 +63619,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, context.endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -63194,6 +64071,7 @@ var ts; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); statements.push(statement); } } @@ -63211,6 +64089,7 @@ var ts; ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); expressions.push(expression); } return expressions; @@ -63631,6 +64510,11 @@ var ts; } return false; } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } /** * Serializes the type of a node for use with decorator type metadata. * @@ -63640,10 +64524,10 @@ var ts; switch (node.kind) { case 152 /* PropertyDeclaration */: case 149 /* Parameter */: - case 156 /* GetAccessor */: return serializeTypeNode(node.type); case 157 /* SetAccessor */: - return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 156 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 154 /* MethodDeclaration */: @@ -63834,11 +64718,11 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: - var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); + return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); case ts.TypeReferenceSerializationKind.BooleanType: @@ -63863,14 +64747,35 @@ var ts; return ts.Debug.assertNever(kind); } } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 71 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 71 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } /** * Serializes an entity name as an expression for decorator type metadata. * * @param node The entity name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * entity name at runtime. */ - function serializeEntityNameAsExpression(node, useFallback) { + function serializeEntityNameAsExpression(node) { switch (node.kind) { case 71 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were @@ -63879,12 +64784,9 @@ var ts; name.flags &= ~8 /* Synthesized */; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. - if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); - } return name; case 146 /* QualifiedName */: - return serializeQualifiedNameAsExpression(node, useFallback); + return serializeQualifiedNameAsExpression(node); } } /** @@ -63894,19 +64796,8 @@ var ts; * @param useFallback A value indicating whether to use logical operators to test for the * qualified name at runtime. */ - function serializeQualifiedNameAsExpression(node, useFallback) { - var left; - if (node.left.kind === 71 /* Identifier */) { - left = serializeEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); - } - else { - left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); - } - return ts.createPropertyAccess(left, node.right); + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); } /** * Gets an expression that points to the global "Symbol" constructor at runtime if it is @@ -64315,7 +65206,8 @@ var ts; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; @@ -64350,8 +65242,13 @@ var ts; /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } ts.setTextRange(enumStatement, node); - ts.setEmitFlags(enumStatement, emitFlags); + ts.addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); // Add a DeclarationMarker for the enum to preserve trailing comments and mark // the end of the declaration. @@ -64369,7 +65266,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -64498,7 +65395,7 @@ var ts; // })(m1 || (m1 = {})); // trailing comment module // ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(statement); return true; } @@ -64533,7 +65430,8 @@ var ts; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; @@ -64567,8 +65465,13 @@ var ts; /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } ts.setTextRange(moduleStatement, node); - ts.setEmitFlags(moduleStatement, emitFlags); + ts.addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); // Add a DeclarationMarker for the namespace to preserve trailing comments and mark // the end of the declaration. @@ -64610,7 +65513,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -65420,7 +66323,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -66027,7 +66930,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -66055,7 +66958,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependStatements(statements, leadingStatements); + ts.addStatementsAfterPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -67150,7 +68053,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -67405,7 +68308,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -67518,7 +68421,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -67628,7 +68531,7 @@ var ts; return 2 /* ReplaceWithReturn */; } // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis(), firstStatement); + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); // If we're actually replacing the original statement, we need to signal this to the caller. if (superCallExpression) { return 1 /* ReplaceSuperCapture */; @@ -67820,7 +68723,7 @@ var ts; captureThisForNode(statements, node, ts.createThis()); } } - function captureThisForNode(statements, node, initializer, originalStatement) { + function captureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -67828,7 +68731,6 @@ var ts; /*type*/ undefined, initializer) ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); - ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); } @@ -68158,7 +69060,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependStatements(statements, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { @@ -68420,7 +69322,7 @@ var ts; var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) - : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement), node, convertedLoopState && resetLabel); + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { @@ -68737,7 +69639,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependStatements(statements_4, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -70412,7 +71314,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -72650,7 +73552,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -72873,7 +73775,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -72936,9 +73838,9 @@ var ts; return visitFunctionDeclaration(node); case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 307 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 308 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -73164,7 +74066,7 @@ var ts; if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { // import "mod"; - return ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); } else { var variables = []; @@ -73185,18 +74087,20 @@ var ts; /*type*/ undefined, ts.getGeneratedNameForNode(node))); } } - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), - /*location*/ node)); + /*location*/ node), + /*original*/ node)); } } else if (namespaceDeclaration && ts.isDefaultImport(node)) { // import d, * as n from "mod"; statements = ts.append(statements, ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node)), - /*location*/ node) + /*location*/ node), + /*original*/ node) ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -73232,20 +74136,20 @@ var ts; var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); } else { - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), /*type*/ undefined, createRequireCall(node)) ], - /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node)); + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); } } else { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); } } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -73274,23 +74178,24 @@ var ts; var statements = []; // export { x, y } from "mod"; if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.setTextRange(ts.createVariableStatement( + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(generatedName, /*type*/ undefined, createRequireCall(node)) ])), - /*location*/ node)); + /*location*/ node), + /* original */ node)); } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); } return ts.singleOrMany(statements); } else { // export * from "mod"; - return ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); } } /** @@ -73396,7 +74301,7 @@ var ts; statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); } if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); } } else { @@ -74142,7 +75047,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -74870,9 +75775,9 @@ var ts; return visitCatchClause(node); case 216 /* Block */: return visitBlock(node); - case 307 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 308 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -75916,7 +76821,8 @@ var ts; 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | - 4 /* GenerateNamesForShadowedTypeParams */; + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; /** * Transforms a ts file into a .d.ts file * This process requires type information, which is retrieved through the emit resolver. Because of this, @@ -75936,6 +76842,7 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, @@ -75944,6 +76851,7 @@ var ts; reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode }; var errorNameNode; var currentSourceFile; @@ -76002,6 +76910,11 @@ var ts; } } } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } function trackSymbol(symbol, enclosingDeclaration, meaning) { if (symbol.flags & 262144 /* TypeParameter */) return; @@ -76029,7 +76942,7 @@ var ts; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; - var refs_1 = ts.createMap(); + refs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) @@ -76043,7 +76956,7 @@ var ts; getSymbolAccessibilityDiagnostic = throwDiagnostic; needsScopeFixMarker = false; resultHasScopeMarker = false; - collectReferences(sourceFile, refs_1); + collectReferences(sourceFile, refs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -76064,7 +76977,7 @@ var ts; bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); - refs_1.forEach(referenceVisitor_1); + refs.forEach(referenceVisitor_1); return bundle; } // Single source file @@ -76092,6 +77005,7 @@ var ts; combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; function getFileReferencesForUsedTypeReferences() { return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; @@ -76309,10 +77223,18 @@ var ts; if (!input) return undefined; // TODO: GH#18217 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); - if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { - var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); - if (newName) { - return ts.createLiteral(newName); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } } } return input; @@ -76841,6 +77763,15 @@ var ts; } return false; } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } function ensureModifiers(node, privateDeclaration) { var currentFlags = ts.getModifierFlags(node); var newFlags = ensureModifierFlags(node, privateDeclaration); @@ -76854,7 +77785,7 @@ var ts; var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; var parentIsFile = node.parent.kind === 277 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { - mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; } return maskModifierFlags(node, mask, additions); @@ -76873,7 +77804,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_8 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -76887,7 +77818,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_8(range); } } return prop; @@ -76913,6 +77844,11 @@ var ts; if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) } @@ -77049,7 +77985,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(309 /* Count */); + var enabledSyntaxKindFeatures = new Array(310 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -77396,7 +78332,7 @@ var ts; if (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { // The relative paths are relative to the common directory @@ -77602,7 +78538,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 304 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -77619,7 +78555,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 304 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -77798,7 +78734,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 304 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -77812,10 +78748,12 @@ var ts; var savedContainerPos = containerPos; var savedContainerEnd = containerEnd; var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments) { + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. containerPos = pos; } - if (!skipTrailingComments) { + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end @@ -78164,17 +79102,17 @@ var ts; if (sourceFile.kind === 278 /* Bundle */) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error var isJs = ts.isSourceFileJavaScript(sourceFile); - var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } @@ -78229,6 +79167,7 @@ var ts; }); var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; + var exportedModulesFromDeclarationEmit; // Emit each output file ts.performance.mark("beforePrint"); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); @@ -78238,6 +79177,7 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -78296,7 +79236,7 @@ var ts; // Setup and perform the transformation to retrieve declarations from the input files var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; - if (emitOnlyDtsFiles && !compilerOptions.declaration) { + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. // Do that here when emitting only dts files nonJsFiles.forEach(collectLinkedAliases); @@ -78325,6 +79265,10 @@ var ts; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } } declarationTransform.dispose(); } @@ -78963,9 +79907,9 @@ var ts; case 262 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return emitCommaList(node); } } @@ -81680,7 +82624,7 @@ var ts; case WatchLogLevel.TriggerOnly: return createFileWatcherWithTriggerLogging; case WatchLogLevel.Verbose: - return createFileWatcherWithLogging; + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; } } function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { @@ -81693,9 +82637,27 @@ var ts; } }; } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { return addWatch(host, file, function (fileName, cbOptional) { - var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); log(triggerredInfo); var start = ts.timestamp(); cb(fileName, cbOptional, passThrough); @@ -81825,7 +82787,7 @@ var ts; } } ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82187,6 +83149,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -82224,7 +83187,8 @@ var ts; var packageIdToSourceFile = ts.createMap(); // Maps from a SourceFile's `.path` to the name of the package it was imported with. var sourceFileToPackageName = ts.createMap(); - var redirectTargetsSet = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -82331,7 +83295,7 @@ var ts; getSourceFileFromReference: getSourceFileFromReference, getLibFileFromReference: getLibFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsMap: redirectTargetsMap, isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -82617,7 +83581,7 @@ var ts; fileChanged = false; newSourceFile = oldSourceFile; // Use the redirect. } - else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { // If a redirected-to source file changes, the redirect may be broken. if (newSourceFile !== oldSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -82746,7 +83710,7 @@ var ts; resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; - redirectTargetsSet = oldProgram.redirectTargetsSet; + redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -82938,10 +83902,7 @@ var ts; } function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { - // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a - // '/// ' directive. - if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { + if (ts.skipTypeChecking(sourceFile, options)) { return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); @@ -83335,7 +84296,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -83413,9 +84374,17 @@ var ts; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path - // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } } // If the file was previously found via a node_modules search, but is now being processed as a root file, // then everything it sucks in may also be marked incorrectly, and needs to be checked again. @@ -83468,7 +84437,7 @@ var ts; // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 - redirectTargetsSet.set(fileFromPackageId.path, true); + redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); @@ -83698,7 +84667,7 @@ var ts; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); allFilesBelongToPath = false; } } @@ -83715,6 +84684,7 @@ var ts; if (sourceFile === undefined) { return undefined; } + sourceFile.path = toPath(refPath); var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } @@ -83728,7 +84698,7 @@ var ts; ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 } function verifyCompilerOptions() { - if (options.strictPropertyInitialization && !options.strictNullChecks) { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { @@ -83788,14 +84758,14 @@ var ts; if (options.composite && rootNames.length < files.length) { var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_10 = function (file) { + var _loop_9 = function (file) { if (normalizedRootNames.every(function (r) { return r !== file; })) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); } }; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var file = sourceFiles_4[_i]; - _loop_10(file); + _loop_9(file); } } if (options.paths) { @@ -83852,7 +84822,7 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } - if (options.declarationMap && !options.declaration) { + if (options.declarationMap && !ts.getEmitDeclarations(options)) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); } if (options.lib && options.noLib) { @@ -83893,6 +84863,10 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } + // Any emit other than common js is error + else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + } } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted @@ -84024,12 +84998,12 @@ var ts; } function createDiagnosticForReference(index, message, arg0, arg1) { var referencesSyntax = getProjectReferencesSyntax(); - if (referencesSyntax) { - if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { - return; - } + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); @@ -84079,14 +85053,6 @@ var ts; } return !!props.length; } - function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { - if (arrayLiteral.elements.length <= index) { - // Out-of-bounds - return false; - } - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); - return false; // TODO: GH#18217 This function always returns `false`!` - } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -84139,7 +85105,8 @@ var ts; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; /** - * Returns the target config filename of a project reference + * Returns the target config filename of a project reference. + * Note: The file might not exist. */ function resolveProjectReferencePath(host, ref) { if (!host.fileExists(ref.path)) { @@ -84159,7 +85126,6 @@ var ts; switch (extension) { case ".ts" /* Ts */: case ".d.ts" /* Dts */: - case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check // These are always allowed. return undefined; case ".tsx" /* Tsx */: @@ -84168,6 +85134,8 @@ var ts; return needJsx() || needAllowJs(); case ".js" /* Js */: return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); } function needJsx() { return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; @@ -84175,6 +85143,9 @@ var ts; function needAllowJs() { return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } } ts.getResolutionDiagnostic = getResolutionDiagnostic; function getModuleNames(_a) { @@ -84196,7 +85167,7 @@ var ts; function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -84207,6 +85178,22 @@ var ts; (function (ts) { var BuilderState; (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.path; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -84219,12 +85206,9 @@ var ts; var checker = program.getTypeChecker(); for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); } } } @@ -84269,6 +85253,7 @@ var ts; function create(newProgram, getCanonicalFileName, oldState) { var fileInfos = ts.createMap(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; var hasCalledUpdateShapeSignature = ts.createMap(); var useOldState = canReuseOldState(referencedMap, oldState); // Create the reference map, and set the file infos @@ -84281,12 +85266,20 @@ var ts; if (newReferences) { referencedMap.set(sourceFile.path, newReferences); } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } } fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); } return { fileInfos: fileInfos, referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, allFilesExcludingDefaultLibraryFile: undefined, allFileNames: undefined @@ -84296,7 +85289,7 @@ var ts; /** * Gets the files affected by the path from the program */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { // Since the operation could be cancelled, the signatures are always stored in the cache // They will be commited once it is safe to use them // eg when calling this api from tsserver, if there is no cancellation of the operation @@ -84306,10 +85299,10 @@ var ts; if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); if (!cacheToUpdateSignature) { // Commit all the signatures in the signature cache updateSignaturesFromCache(state, signatureCache); @@ -84331,8 +85324,9 @@ var ts; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { return false; @@ -84349,6 +85343,9 @@ var ts; var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } } else { latestSignature = prevSignature; // TODO: GH#18217 @@ -84357,6 +85354,44 @@ var ts; cacheToUpdateSignature.set(sourceFile.path, latestSignature); return !prevSignature || latestSignature !== prevSignature; } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -84466,7 +85501,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -84486,7 +85521,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 queue, getReferencedByPaths(state, currentPath)); } @@ -84517,7 +85552,8 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -84553,6 +85589,10 @@ var ts; var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); } } }); @@ -84574,14 +85614,14 @@ var ts; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { - var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var seenAffectedFiles = state.seenAffectedFiles; var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 while (affectedFilesIndex < affectedFiles.length) { var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.path)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - semanticDiagnosticsPerFile.delete(affectedFile.path); + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); return affectedFile; } seenAffectedFiles.set(affectedFile.path, true); @@ -84593,6 +85633,7 @@ var ts; // Commit the changes in file signature ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); state.affectedFiles = undefined; } // Get next changed file @@ -84610,13 +85651,66 @@ var ts; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; - state.semanticDiagnosticsPerFile.delete(nextKey.value); state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return false; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } /** * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly @@ -84883,6 +85977,7 @@ var ts; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -84940,6 +86035,7 @@ var ts; function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); @@ -84979,17 +86075,19 @@ var ts; perDirectoryResolvedModuleNames.clear(); nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); - clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); @@ -85041,7 +86139,7 @@ var ts; perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); - watchFailedLookupLocationOfResolution(resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } @@ -85137,14 +86235,23 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - // Always watch root directory recursively - return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, "/node_modules/")) { + while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } @@ -85173,16 +86280,25 @@ var ts; function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); } - function watchFailedLookupLocationOfResolution(resolution) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { // No need to set the resolution refCount - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { - return; - } - if (resolution.refCount !== undefined) { - resolution.refCount++; - return; + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } } - resolution.refCount = 1; + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); var failedLookupLocations = resolution.failedLookupLocations; var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { @@ -85197,6 +86313,7 @@ var ts; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); } if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); setAtRoot = true; } else { @@ -85205,10 +86322,19 @@ var ts; } } if (setAtRoot) { - // This is always recursive - setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { @@ -85220,7 +86346,7 @@ var ts; } } function stopWatchFailedLookupLocationOfResolution(resolution) { - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + if (!resolution.refCount) { return; } resolution.refCount--; @@ -85443,23 +86569,36 @@ var ts; } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); -// Used by importFixes to synthesize import module specifiers. +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { // Note: importingSourceFile is just for usesJsExtensionOnImports - function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences) { + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, toFileName, info.getCanonicalFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { + var isBundle = (compilerOptions.out || compilerOptions.outFile); + if (isBundle && host.getCommonSourceDirectory) { + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); + } + var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; + return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + } + moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) return [[ambient]]; @@ -85467,7 +86606,8 @@ var ts; if (!files) { return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); } - var modulePaths = getAllModulePaths(files, ts.getSourceFileOfNode(moduleSymbol.valueDeclaration).fileName, info.getCanonicalFileName, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); @@ -85552,64 +86692,66 @@ var ts; return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; }) || false; } - function discoverProbableSymlinks(files, getCanonicalFileName, host) { + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); var symlinks = ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; }); }); - var result = ts.createMap(); - if (symlinks) { - var currentDirectory = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { - var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; - var resolvedParts = ts.getPathComponents(ts.toPath(resolvedPath, currentDirectory, getCanonicalFileName)); - var originalParts = ts.getPathComponents(ts.toPath(originalPath, currentDirectory, getCanonicalFileName)); - while (compareStrings(resolvedParts[resolvedParts.length - 1], originalParts[originalParts.length - 1]) === 0 /* EqualTo */) { - resolvedParts.pop(); - originalParts.pop(); - } - result.set(ts.getPathFromPathComponents(originalParts), ts.getPathFromPathComponents(resolvedParts)); - } + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); } return result; } - function getAllModulePathsUsingIndirectSymlinks(files, target, getCanonicalFileName, host) { - var links = discoverProbableSymlinks(files, getCanonicalFileName, host); - var paths = ts.arrayFrom(links.keys()); - var options; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, paths_2 = paths; _i < paths_2.length; _i++) { - var path = paths_2[_i]; - var resolved = links.get(path); - if (compareStrings(target.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */) { - var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - if (!options) - options = []; - options.push(option); - } - } - } - if (options) { - options.push(target); // Since these are speculative, we also include the original resolved name as a possibility - return options; - } - return [target]; - } /** * Looks for existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(files, importedFileName, getCanonicalFileName, host) { - var symlinks = ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === importedFileName ? res.originalPath : undefined; - }); + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } }); - return symlinks.length === 0 ? getAllModulePathsUsingIndirectSymlinks(files, ts.getNormalizedAbsolutePath(importedFileName, host.getCurrentDirectory ? host.getCurrentDirectory() : ""), getCanonicalFileName, host) : symlinks; + result.push.apply(result, targets); + return result; } function getRelativePathNParents(relativePath) { var components = ts.getPathComponents(relativePath); @@ -85622,8 +86764,8 @@ var ts; return components.length - 1; } function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { return decl.name.text; } } @@ -85633,10 +86775,7 @@ var ts; var patternText_1 = _a[_i]; var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { + if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && @@ -85749,7 +86888,7 @@ var ts; partEnd = fullPath.indexOf("/", partStart + 1); switch (state) { case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { topLevelNodeModulesIndex = partStart; topLevelPackageNameIndex = partEnd; state = 1 /* NodeModules */; @@ -85766,7 +86905,7 @@ var ts; } break; case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { state = 1 /* NodeModules */; } else { @@ -85951,6 +87090,7 @@ var ts; createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; } var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); @@ -86079,16 +87219,15 @@ var ts; }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); - if (configFileName) { + if (configFileName && !host.configFileParsingResult) { newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); - if (host.configFileParsingResult) { - setConfigFileParsingResult(host.configFileParsingResult); - } - else { - ts.Debug.assert(!rootFileNames); - parseConfigFile(); - } + ts.Debug.assert(!rootFileNames); + parseConfigFile(); newLine = updateNewLine(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); @@ -86636,7 +87775,7 @@ var ts; } var outputs = []; outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); - if (configFile.options.declaration && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); if (configFile.options.declarationMap) { @@ -86651,7 +87790,7 @@ var ts; } var outputs = []; outputs.push(project.options.outFile); - if (project.options.declaration) { + if (ts.getEmitDeclarations(project.options)) { var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { @@ -86803,6 +87942,7 @@ var ts; return builder.cleanAllProjects(); } if (watch) { + builder.buildAllProjects(); builder.startWatching(); return undefined; } @@ -86859,7 +87999,7 @@ var ts; // Everything is broken - we don't even know what to watch. Give up. return; } - var _loop_11 = function (resolved) { + var _loop_10 = function (resolved) { var cfg = configFileCache.parseConfigFile(resolved); if (cfg) { // Watch this file @@ -86886,7 +88026,7 @@ var ts; }; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var resolved = _a[_i]; - _loop_11(resolved); + _loop_10(resolved); } function invalidateProjectAndScheduleBuilds(resolved) { invalidateProject(resolved); @@ -87056,7 +88196,7 @@ var ts; }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { resultFlags |= BuildResultFlags.SyntaxErrors; for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { @@ -87067,7 +88207,7 @@ var ts; return resultFlags; } // Don't emit .d.ts if there are decl file errors - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { resultFlags |= BuildResultFlags.DeclarationEmitErrors; @@ -87121,15 +88261,16 @@ var ts; if (context.options.dry) { return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) + if (context.options.verbose) { buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { var file = outputs_1[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file)); + priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); } compilerHost.setModifiedTime(file, now); } @@ -87327,7 +88468,7 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile); + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; if (inputTime > newestInputFileTime) { newestInputFileName = inputFile; newestInputFileTime = inputTime; @@ -87356,7 +88497,7 @@ var ts; missingOutputFileName = output; break; } - var outputTime = host.getModifiedTime(output); + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; if (outputTime < oldestOutputFileTime) { oldestOutputFileTime = outputTime; oldestOutputFileName = output; @@ -87381,7 +88522,8 @@ var ts; newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } else { - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, host.getModifiedTime(output)); + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } @@ -87500,7 +88642,7 @@ var ts; // Don't report status on "solution" projects break; default: - ts.assertTypeIsNever(status); + ts.assertType(status); } } ts.formatUpToDateStatus = formatUpToDateStatus; @@ -88200,7 +89342,7 @@ var ts; case 240 /* TypeAliasDeclaration */: case 166 /* TypeLiteral */: return 2 /* Type */; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; case 276 /* EnumMember */: @@ -88328,16 +89470,20 @@ var ts; return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 189 /* CallExpression */); + return isCallOrNewExpressionTargetWorker(node, ts.isCallExpression); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 190 /* NewExpression */); + return isCallOrNewExpressionTargetWorker(node, ts.isNewExpression); } ts.isNewExpressionTarget = isNewExpressionTarget; - function isCallOrNewExpressionTarget(node, kind) { + function isCallOrNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallOrNewExpression); + } + ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget; + function isCallOrNewExpressionTargetWorker(node, pred) { var target = climbPastPropertyAccess(node); - return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && pred(target.parent) && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -88451,7 +89597,7 @@ var ts; case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; case 240 /* TypeAliasDeclaration */: case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return "type" /* typeElement */; case 241 /* EnumDeclaration */: return "enum" /* enumElement */; case 235 /* VariableDeclaration */: @@ -88502,7 +89648,7 @@ var ts; case 6 /* Prototype */: return "local class" /* localClassElement */; default: { - ts.assertTypeIsNever(kind); + ts.assertType(kind); return "" /* unknown */; } } @@ -88780,7 +89926,7 @@ var ts; var current = sourceFile; outer: while (true) { // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { var child = _a[_i]; var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { @@ -88991,7 +90137,21 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(tokenIn, sourceFile) { + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { var token = tokenIn; // This function determines if the node could be type argument position // Since during editing, when type argument list is not complete, @@ -89071,7 +90231,7 @@ var ts; } return undefined; } - ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; /** * Returns true if the cursor at position in sourceFile is within a comment. * @@ -89203,6 +90363,10 @@ var ts; return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { return ts.createTextSpanFromBounds(range.pos, range.end); } @@ -89222,6 +90386,7 @@ var ts; ts.typeKeywords = [ 119 /* AnyKeyword */, 122 /* BooleanKeyword */, + 86 /* FalseKeyword */, 128 /* KeyOfKeyword */, 131 /* NeverKeyword */, 95 /* NullKeyword */, @@ -89229,6 +90394,7 @@ var ts; 135 /* ObjectKeyword */, 137 /* StringKeyword */, 138 /* SymbolKeyword */, + 101 /* TrueKeyword */, 105 /* VoidKeyword */, 140 /* UndefinedKeyword */, 141 /* UniqueKeyword */, @@ -89240,8 +90406,7 @@ var ts; ts.isTypeKeyword = isTypeKeyword; /** True if the symbol is for an external module, as opposed to a namespace. */ function isExternalModuleSymbol(moduleSymbol) { - ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); - return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; function nodeSeenTracker() { @@ -89265,13 +90430,13 @@ var ts; } ts.repeatString = repeatString; function skipConstraint(type) { - return type.isTypeParameter() ? type.getConstraint() : type; // TODO: GH#18217 + return type.isTypeParameter() ? type.getConstraint() || type : type; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { return name.kind === 147 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal - ? ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined + ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.getTextOfIdentifierOrLiteral(name); } ts.getNameFromPropertyName = getNameFromPropertyName; @@ -89326,6 +90491,14 @@ var ts; } } ts.getQuotePreference = getQuotePreference; + function getQuoteFromPreference(qp) { + switch (qp) { + case 0 /* Single */: return "'"; + case 1 /* Double */: return '"'; + default: return ts.Debug.assertNever(qp); + } + } + ts.getQuoteFromPreference = getQuoteFromPreference; function symbolNameNoDefault(symbol) { var escaped = symbolEscapedNameNoDefault(symbol); return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); @@ -89383,56 +90556,6 @@ var ts; return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; } ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; - var NodeSet = /** @class */ (function () { - function NodeSet() { - this.map = ts.createMap(); - } - NodeSet.prototype.add = function (node) { - this.map.set(String(ts.getNodeId(node)), node); - }; - NodeSet.prototype.has = function (node) { - return this.map.has(String(ts.getNodeId(node))); - }; - NodeSet.prototype.forEach = function (cb) { - this.map.forEach(cb); - }; - NodeSet.prototype.some = function (pred) { - return ts.forEachEntry(this.map, pred) || false; - }; - return NodeSet; - }()); - ts.NodeSet = NodeSet; - var NodeMap = /** @class */ (function () { - function NodeMap() { - this.map = ts.createMap(); - } - NodeMap.prototype.get = function (node) { - var res = this.map.get(String(ts.getNodeId(node))); - return res && res.value; - }; - NodeMap.prototype.getOrUpdate = function (node, setValue) { - var res = this.get(node); - if (res) - return res; - var value = setValue(); - this.set(node, value); - return value; - }; - NodeMap.prototype.set = function (node, value) { - this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); - }; - NodeMap.prototype.has = function (node) { - return this.map.has(String(ts.getNodeId(node))); - }; - NodeMap.prototype.forEach = function (cb) { - this.map.forEach(function (_a) { - var node = _a.node, value = _a.value; - return cb(value, node); - }); - }; - return NodeMap; - }()); - ts.NodeMap = NodeMap; function getParentNodeInSpan(node, file, span) { if (!node) return undefined; @@ -89463,6 +90586,14 @@ var ts; } } ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -89473,13 +90604,24 @@ var ts; ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios var displayParts; var lineStart; var indent; + var length; resetWriter(); var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { - displayParts: function () { return displayParts; }, + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, @@ -89508,23 +90650,35 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { + if (length > absoluteMaximumLength) + return; if (lineStart) { var indentString = ts.getIndentString(indent); if (indentString) { + length += indentString.length; displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); } lineStart = false; } } function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(displayPart(text, kind)); } function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(symbolPart(text, symbol)); } function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; displayParts.push(lineBreakPart()); lineStart = true; } @@ -89532,6 +90686,7 @@ var ts; displayParts = []; lineStart = true; indent = 0; + length = 0; } } function symbolPart(text, symbol) { @@ -89725,8 +90880,30 @@ var ts; return clone; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; - function getSynthesizedDeepCloneWorker(node) { - var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone; + if (node && ts.isIdentifier(node) && renameMap && checker) { + var symbol = checker.getSymbolAtLocation(node); + var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); + if (renameInfo) { + clone = ts.createIdentifier(renameInfo.text); + } + } + if (!clone) { + clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + } + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + if (callback && node) + callback(node, clone); + return clone; + } + ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames; + function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) { + var visited = (renameMap || checker || callback) ? + ts.visitEachChild(node, wrapper, ts.nullTransformationContext) : + ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. var clone_7 = ts.getSynthesizedClone(node); @@ -89743,6 +90920,9 @@ var ts; // would have made. visited.parent = undefined; return visited; + function wrapper(node) { + return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback); + } } function getSynthesizedDeepClones(nodes, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = true; } @@ -90497,18 +91677,18 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 297 /* JSDocReturnTag */: + case 298 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -90881,7 +92061,7 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_12 = function (name, kind) { + var _loop_11 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind)); @@ -90889,7 +92069,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_12(name, kind); + _loop_11(name, kind); } } } @@ -90905,7 +92085,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_13 = function (moduleName) { + var _loop_12 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); @@ -90913,7 +92093,7 @@ var ts; }; for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { var moduleName = _f[_e]; - _loop_13(moduleName); + _loop_12(moduleName); } } if (!foundGlobal) { @@ -91170,6 +92350,19 @@ var ts; (function (ts) { var Completions; (function (Completions) { + var SymbolOriginInfoKind; + (function (SymbolOriginInfoKind) { + SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 0] = "ThisType"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 1] = "SymbolMemberNoExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 2] = "SymbolMemberExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 3] = "Export"; + })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); + function originIsSymbolMember(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 1 /* SymbolMemberNoExport */; + } + function originIsExport(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 3 /* Export */; + } var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; @@ -91193,8 +92386,8 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) - return undefined; // TODO: GH#18217 + if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined @@ -91258,20 +92451,22 @@ var ts; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; - if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { + if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
- // The completion list at "1" will contain "div" with type any + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, - entries: [{ - name: tagName.getFullText(), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: "0", - }] }; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { @@ -91340,12 +92535,12 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (origin && origin.type === "this-type") { + if (origin && origin.kind === 0 /* ThisType */) { insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. - else if ((origin && origin.type === "symbol-member" || needsConvertPropertyAccess) && propertyAccessToConvert) { + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. @@ -91376,7 +92571,7 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(!!origin && origin.type === "export"), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), insertText: insertText, replacementSpan: replacementSpan, @@ -91402,7 +92597,7 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); @@ -91483,6 +92678,8 @@ var ts; return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 171 /* UnionType */: + return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; default: return undefined; } @@ -91599,7 +92796,7 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -91634,7 +92831,7 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -91677,14 +92874,14 @@ var ts; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; } - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, allSourceFiles, preferences) { + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo || symbolOriginInfo.type !== "export") { + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { return { codeActions: undefined, sourceDisplay: undefined }; } var moduleSymbol = symbolOriginInfo.moduleSymbol; var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, allSourceFiles, formatContext, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { @@ -91833,7 +93030,7 @@ var ts; currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 302 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 303 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -91890,6 +93087,9 @@ var ts; case 146 /* QualifiedName */: node = parent.left; break; + case 242 /* ModuleDeclaration */: + node = parent.name; + break; case 181 /* ImportType */: case 212 /* MetaProperty */: node = parent; @@ -91996,11 +93196,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: - case 297 /* JSDocReturnTag */: - case 299 /* JSDocTypeTag */: - case 301 /* JSDocTypedefTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: + case 298 /* JSDocReturnTag */: + case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypedefTag */: return true; default: return false; @@ -92013,8 +93213,11 @@ var ts; var isImportType = ts.isLiteralImportTypeNode(node); var isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !node.isTypeOf) || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); - var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile)); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)); if (ts.isEntityName(node) || isImportType) { + var isNamespaceName = ts.isModuleDeclaration(node.parent); + if (isNamespaceName) + isNewIdentifierLocation = true; var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { symbol = ts.skipAlias(symbol, typeChecker); @@ -92023,14 +93226,17 @@ var ts; var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; - var isValidAccess = allowTypeOrValue ? - // Any kind is allowed when dotting off namespace in internal import equals declaration - function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : - isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + var isValidAccess = isNamespaceName + // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. + ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + : allowTypeOrValue ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { - var symbol_2 = exportedSymbols_1[_i]; - if (isValidAccess(symbol_2)) { - symbols.push(symbol_2); + var exportedSymbol = exportedSymbols_1[_i]; + if (isValidAccess(exportedSymbol)) { + symbols.push(exportedSymbol); } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). @@ -92081,7 +93287,9 @@ var ts; var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { symbols.push(firstAccessibleSymbol); - symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = { type: "symbol-member" }; + var moduleSymbol = firstAccessibleSymbol.parent; + symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = + !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) ? { kind: 1 /* SymbolMemberNoExport */ } : { kind: 2 /* SymbolMemberExport */, moduleSymbol: moduleSymbol, isDefaultExport: false }; } } else { @@ -92171,7 +93379,7 @@ var ts; if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 0 /* ThisType */ }; symbols.push(symbol); } } @@ -92213,7 +93421,7 @@ var ts; } function filterGlobalCompletion(symbols) { var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile); + var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) keywordFilters = 5 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { @@ -92306,7 +93514,7 @@ var ts; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + var origin = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; @@ -92372,7 +93580,8 @@ var ts; function isNewIdentifierDefinitionLocation(previousToken) { if (previousToken) { var containingNodeKind = previousToken.parent.kind; - switch (previousToken.kind) { + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(previousToken)) { case 26 /* CommaToken */: return containingNodeKind === 189 /* CallExpression */ // func( a, | || containingNodeKind === 155 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ @@ -92409,13 +93618,6 @@ var ts; case 113 /* ProtectedKeyword */: return containingNodeKind === 152 /* PropertyDeclaration */; // class A{ public | } - // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: - return true; - } } return false; } @@ -92958,7 +94160,7 @@ var ts; case 3 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); case 4 /* FunctionLikeBodyKeywords */: - return !isClassMemberCompletionKeyword(kind); + return isFunctionLikeBodyKeyword(kind); case 5 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: @@ -92981,6 +94183,9 @@ var ts; return ts.isClassMemberModifier(kind); } } + function isFunctionLikeBodyKeyword(kind) { + return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } @@ -93027,7 +94232,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 303 /* SyntaxList */: + case 304 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -93135,7 +94340,7 @@ var ts; return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; if (!sourceFilesSet.has(fileName)) { - ts.Debug.assert(program.redirectTargetsSet.has(fileName)); + ts.Debug.assert(program.redirectTargetsMap.has(fileName)); var redirectTarget_1 = program.getSourceFile(fileName); var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; @@ -94447,7 +95652,8 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -94852,7 +96058,7 @@ var ts; - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. */ var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); - if (exposedByParent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } var scope; @@ -95485,7 +96691,8 @@ var ts; // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - var res_1 = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), fromRoot); + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); if (res_1) return res_1; // If the location is name of property symbol from object literal destructuring pattern @@ -95550,14 +96757,6 @@ var ts; return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); }); } - /** Gets all symbols for one property. Does not get symbols for every property. */ - function getPropertySymbolsFromContextualType(node, checker) { - var contextualType = checker.getContextualType(node.parent); - var name = ts.getNameFromPropertyName(node.name); - var symbol = contextualType && name && contextualType.getProperty(name); - return symbol ? [symbol] : - contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; // TODO: GH#18217 - } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class @@ -95641,11 +96840,11 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName); - var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); @@ -95653,16 +96852,28 @@ var ts; } ts.getEditsForFileRename = getEditsForFileRename; // exported for tests - function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName) { + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return function (path) { - if (getCanonicalFileName(path) === canonicalOldPath) + var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) return newFileOrDirPath; - var suffix = ts.tryRemoveDirectoryPrefix(path, canonicalOldPath, getCanonicalFileName); + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; - }; + } } ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); + } function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; if (!configFile) @@ -95734,7 +96945,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { var allFiles = program.getSourceFiles(); - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -95756,17 +96967,17 @@ var ts; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. // TODO:GH#18217 - ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, program) + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences) + ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_14(sourceFile); + _loop_13(sourceFile); } } function combineNormal(pathA, pathB) { @@ -95786,14 +96997,14 @@ var ts; var resolved = host.resolveModuleNames ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); - return getSourceFileToImportFromResolved(resolved, oldToNew, program); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); } } - function getSourceFileToImportFromResolved(resolved, oldToNew, program) { - return resolved && ((resolved.resolvedModule && getIfInProgram(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfInProgram)); - function getIfInProgram(oldLocation) { + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); + function getIfExists(oldLocation) { var newLocation = oldToNew(oldLocation); - return program.getSourceFile(oldLocation) || newLocation !== undefined && program.getSourceFile(newLocation) + return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } : undefined; } @@ -95860,12 +97071,12 @@ var ts; // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || - // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias - symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { return [sigInfo]; } else { - var defs = getDefinitionFromSymbol(typeChecker, symbol, node); + var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; // For a 'super()' call, put the signature first, else put the variable first. return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } @@ -95892,13 +97103,12 @@ var ts; // bar(({pr/*goto*/op1})=>{}); if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && (node === (parent.propertyName || parent.name))) { + var name_5 = ts.getNameFromPropertyName(node); var type = typeChecker.getTypeAtLocation(parent.parent); - if (type) { - var propSymbols = ts.getPropertySymbolsFromType(type, node); - if (propSymbols) { - return ts.flatMap(propSymbols, function (propSymbol) { return getDefinitionFromSymbol(typeChecker, propSymbol, node); }); - } - } + return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_5); + return prop && getDefinitionFromSymbol(typeChecker, prop, node); + }); } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. @@ -95910,10 +97120,13 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element && typeChecker.getContextualType(element.parent)) { - return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { - return getDefinitionFromSymbol(typeChecker, propertySymbol, node); - }); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -95953,16 +97166,32 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); - if (!type) { + if (!symbol) return undefined; - } - if (type.isUnion() && !(type.flags & 32 /* Enum */)) { - return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); - } - return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); + var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); + var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); + // If a function returns 'void' or some other type with no definition, just return the function definition. + return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function definitionFromType(type, checker, node) { + return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) { + return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node); + }); + } + function tryGetReturnTypeOfFunction(symbol, type, checker) { + // If the type is just a function's inferred type, + // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway. + if (type.symbol === symbol || + // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { + var sigs = type.getCallSignatures(); + if (sigs.length === 1) + return checker.getReturnTypeOfSignature(ts.first(sigs)); + } + return undefined; + } function getDefinitionAndBoundSpan(program, sourceFile, position) { var definitions = getDefinitionAtPosition(program, sourceFile, position); if (!definitions || definitions.length === 0) { @@ -96037,7 +97266,7 @@ var ts; } } function getCallSignatureDefinition() { - return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) : undefined; } @@ -96111,48 +97340,83 @@ var ts; var JsDoc; (function (JsDoc) { var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", "augments", "author", - "argument", "borrows", "callback", "class", + "classdesc", "constant", "constructor", "constructs", + "copyright", "default", "deprecated", "description", + "emits", + "enum", "event", "example", + "exports", "extends", + "external", "field", - "fileOverview", + "file", + "fileoverview", + "fires", "function", + "generator", + "global", + "hideconstructor", + "host", "ignore", - "inheritDoc", + "implements", + "inheritdoc", "inner", + "instance", + "interface", + "kind", "lends", - "link", - "memberOf", + "license", + "listens", + "member", + "memberof", "method", + "mixes", + "module", "name", "namespace", + "override", + "package", "param", "private", - "prop", "property", + "protected", "public", + "readonly", "requires", "returns", "see", "since", "static", + "summary", "template", + "this", "throws", + "todo", + "tutorial", "type", "typedef", - "version" + "var", + "variation", + "version", + "virtual", + "yields" ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; @@ -96180,11 +97444,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: return [declaration]; case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -96207,14 +97471,14 @@ var ts; switch (tag.kind) { case 293 /* JSDocAugmentsTag */: return withNode(tag.class); - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: - case 302 /* JSDocPropertyTag */: - case 296 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -96340,13 +97604,15 @@ var ts; * be performed. */ function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { - // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); + if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { + // Non-empty comment already exists. return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var tokenStart = tokenAtPos.getStart(sourceFile); - if (!tokenAtPos || tokenStart < position) { + // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.) + if (!existingDocComment && tokenStart < position) { return undefined; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); @@ -96395,45 +97661,48 @@ var ts; }).join(""); } function getCommentOwnerInfo(tokenAtPos) { - for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 153 /* MethodSignature */: - var parameters = commentOwner.parameters; - return { commentOwner: commentOwner, parameters: parameters }; - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 151 /* PropertySignature */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 240 /* TypeAliasDeclaration */: - return { commentOwner: commentOwner }; - case 217 /* 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 277 /* SourceFile */: - return undefined; - case 242 /* 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 === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 202 /* 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.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + } + function getCommentOwnerInfoWorker(commentOwner) { + switch (commentOwner.kind) { + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 153 /* MethodSignature */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 273 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer); + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 151 /* PropertySignature */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 240 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; + case 217 /* 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 277 /* SourceFile */: + return "quit"; + case 242 /* 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 === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 202 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + return "quit"; } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; } } } @@ -96472,9 +97741,9 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_15 = function (sourceFile) { + var _loop_14 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { + if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; } sourceFile.getNamedDeclarations().forEach(function (declarations, name) { @@ -96484,7 +97753,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_15(sourceFile); + _loop_14(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -96527,45 +97796,28 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - if (name && ts.isPropertyNameLiteral(name)) { - containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); - return true; - } - else if (name && name.kind === 147 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; - } + return !!name && (pushLiteral(name, containers) || name.kind === 147 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // // [X.Y.Z]() { } - function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - if (ts.isPropertyNameLiteral(expression)) { - var text = ts.getTextOfIdentifierOrLiteral(expression); - if (includeLastPortion) { - containers.unshift(text); - } - return true; - } - if (ts.isPropertyAccessExpression(expression)) { - if (includeLastPortion) { - containers.unshift(expression.name.text); - } - return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true); - } - return false; + function tryAddComputedPropertyName(expression, containers) { + return pushLiteral(expression, containers) + || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers); + } + function pushLiteral(node, containers) { + return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true); } 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 && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { + if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } + // Don't include the last portion. + containers.shift(); // Now, walk up our containers, adding all their names to the container array. var container = ts.getContainerNode(declaration); while (container) { @@ -96574,7 +97826,7 @@ var ts; } container = ts.getContainerNode(container); } - return containers; + return containers.reverse(); } function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. @@ -96713,7 +97965,7 @@ var ts; /** Call after calling `startNode` and adding children to it. */ function endNode() { if (parent.children) { - mergeChildren(parent.children); + mergeChildren(parent.children, parent); sortChildren(parent.children); } parent = parentsStack.pop(); @@ -96869,7 +98121,7 @@ var ts; } } /** Merge declarations of the same kind. */ - function mergeChildren(children) { + function mergeChildren(children, node) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var declName = ts.getNameOfDeclaration(child.node); @@ -96886,7 +98138,7 @@ var ts; if (itemsWithSameName instanceof Array) { for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { var itemWithSameName = itemsWithSameName_1[_i]; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } } @@ -96895,7 +98147,7 @@ var ts; } else { var itemWithSameName = itemsWithSameName; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } nameToItems.set(name, [itemWithSameName, child]); @@ -96903,16 +98155,16 @@ var ts; } }); } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { merge(a, b); return true; } return false; } /** a and b have the same name, but they may not be mergeable. */ - function shouldReallyMerge(a, b) { - if (a.kind !== b.kind) { + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { return false; } switch (a.kind) { @@ -96927,6 +98179,12 @@ var ts; return true; } } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { @@ -96943,7 +98201,7 @@ var ts; } target.children = ts.concatenate(target.children, source.children); if (target.children) { - mergeChildren(target.children); + mergeChildren(target.children, target); sortChildren(target.children); } } @@ -96965,7 +98223,7 @@ var ts; return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); - if (declName) { + if (declName && ts.isPropertyName(declName)) { return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { @@ -97042,7 +98300,7 @@ var ts; case 242 /* ModuleDeclaration */: case 277 /* SourceFile */: case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return true; case 155 /* Constructor */: @@ -97143,7 +98401,7 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 242 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217 + return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { return !member.name || member.name.kind === 147 /* ComputedPropertyName */; @@ -97665,6 +98923,23 @@ var ts; return spanForObjectOrArrayLiteral(n); case 185 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); + case 258 /* JsxElement */: + return spanForJSXElement(n); + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 17 /* OpenBraceToken */; } @@ -97973,15 +99248,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_16 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_4 = _loop_16(start); - if (typeof state_4 === "object") - return state_4.value; + var state_3 = _loop_15(start); + if (typeof state_3 === "object") + return state_3.value; } return -1; } @@ -98523,7 +99798,7 @@ var ts; if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 147 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); @@ -98582,17 +99857,11 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - var ArgumentListKind; - (function (ArgumentListKind) { - ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; - ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; - ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; - ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind || (ArgumentListKind = {})); var InvocationKind; (function (InvocationKind) { InvocationKind[InvocationKind["Call"] = 0] = "Call"; InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual"; })(InvocationKind || (InvocationKind = {})); function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { var typeChecker = program.getTypeChecker(); @@ -98602,93 +99871,124 @@ var ts; // We are at the beginning of the file return undefined; } - if (shouldCarefullyCheckContext(triggerReason)) { - // In the middle of a string, don't provide signature help unless the user explicitly requested it. - if (ts.isInString(sourceFile, position, startingToken)) { - return undefined; - } + // Only need to be careful if the user typed a character and signature help wasn't showing. + var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { + return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); - // Semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - if (ts.isSourceFileJavaScript(sourceFile)) { - return createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken); - } - return undefined; + return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function shouldCarefullyCheckContext(reason) { - // Only need to be careful if the user typed a character and signature help wasn't showing. - return !!reason && reason.kind === "characterTyped"; - } - function getCandidateInfo(argumentInfo, checker) { - var invocation = argumentInfo.invocation; - if (invocation.kind === 0 /* Call */) { - var candidates = []; - var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = _a.invocation, argumentCount = _a.argumentCount; + switch (invocation.kind) { + case 0 /* Call */: { + if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { + return undefined; + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + } + case 1 /* TypeArgs */: { + if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + case 2 /* Contextual */: + return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + default: + return ts.Debug.assertNever(invocation); } - else { - var type = checker.getTypeAtLocation(invocation.called); // TODO: GH#18217 - var signatures = ts.isNewExpression(invocation.called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); - var candidates = signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= argumentInfo.argumentCount; }); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + function isSyntacticOwner(startingToken, node, sourceFile) { + if (!ts.isCallOrNewExpression(node)) + return false; + var invocationChildren = node.getChildren(sourceFile); + switch (startingToken.kind) { + case 19 /* OpenParenToken */: + return ts.contains(invocationChildren, startingToken); + case 26 /* CommaToken */: { + var containingList = ts.findContainingList(startingToken); + return !!containingList && ts.contains(invocationChildren, containingList); + } + case 27 /* LessThanToken */: + return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + default: + return false; } } function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + if (argumentInfo.invocation.kind === 2 /* Contextual */) + return undefined; // See if we can find some symbol with the call expression name that has call signatures. var expression = getExpressionFromInvocation(argumentInfo.invocation); - var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; - if (!name || !name.escapedText) { - return undefined; - } + var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined; var typeChecker = program.getTypeChecker(); - var _loop_17 = function (sourceFile) { - var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = nameToDeclarations.get(name.text); - if (declarations) { - var _loop_18 = function (declaration) { - var symbol = declaration.symbol; - if (symbol) { - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); - if (type) { - var callSignatures_1 = type.getCallSignatures(); - if (callSignatures_1 && callSignatures_1.length) { - return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; - } - } - } - }; - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - var state_6 = _loop_18(declaration); - if (typeof state_6 === "object") - return state_6; + return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) { + return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) { + var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration); + var callSignatures = type && type.getCallSignatures(); + if (callSignatures && callSignatures.length) { + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); }); } - } - }; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - var state_5 = _loop_17(sourceFile); - if (typeof state_5 === "object") - return state_5.value; - } + }); + }); + } + function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(calledExpression, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); - return !info || info.kind === 0 /* TypeArguments */ || info.invocation.kind === 1 /* TypeArgs */ ? undefined + return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; } SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; + function getArgumentOrParameterListInfo(node, sourceFile) { + var info = getArgumentOrParameterListAndIndex(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex; + var argumentCount = getArgumentCount(list); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + } + function getArgumentOrParameterListAndIndex(node, sourceFile) { + if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. + return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; + } + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + var list = ts.findContainingList(node); + return list && { list: list, argumentIndex: getArgumentIndex(list, node) }; + } + } /** * Returns relevant information for the argument list and the current argument if we are * in the argument of an invocation; returns undefined otherwise. @@ -98697,8 +99997,6 @@ var ts; var parent = node.parent; if (ts.isCallOrNewExpression(parent)) { var invocation = parent; - var list = void 0; - var argumentIndex = void 0; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a signature help session // 2. The token is either not associated with a list, or ends a list, so the session should end @@ -98713,32 +100011,12 @@ var ts; // Case 3: // foo(a#, #b#) -> The token is buried inside a list, and should give signature help // Find out if 'node' is an argument, a type argument, or neither - if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { - // Find the list that starts right *after* the < or ( token. - // If the user has just opened a list, consider this item 0. - list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); - ts.Debug.assert(list !== undefined); - argumentIndex = 0; - } - else { - // findListItemInfo can return undefined if we are not in parent's argument list - // or type argument list. This includes cases where the cursor is: - // - To the right of the closing parenthesis, non-substitution template, or template tail. - // - Between the type arguments and the arguments (greater than token) - // - On the target of the call (parent.func) - // - On the 'new' keyword in a 'new' expression - list = ts.findContainingList(node); - if (!list) - return undefined; - argumentIndex = getArgumentIndex(list, node); - } - var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; - var argumentCount = getArgumentCount(list); - if (argumentIndex !== 0) { - ts.Debug.assertLessThan(argumentIndex, argumentCount); - } - var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var info = getArgumentOrParameterListInfo(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos; + return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { // Check if we're actually inside the template; @@ -98746,6 +100024,7 @@ var ts; if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); } + return undefined; } else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { var templateExpression = parent; @@ -98774,7 +100053,7 @@ var ts; var attributeSpanStart = parent.attributes.pos; var attributeSpanEnd = ts.skipTrivia(sourceFile.text, parent.attributes.end, /*stopAfterLineBreak*/ false); return { - kind: 3 /* JSXAttributesArguments */, + isTypeParameterList: false, invocation: { kind: 0 /* Call */, node: parent }, argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart), argumentIndex: 0, @@ -98782,15 +100061,67 @@ var ts; }; } else { - var typeArgInfo = ts.isPossiblyTypeArgumentPosition(node, sourceFile); + var typeArgInfo = ts.getPossibleTypeArgumentsInfo(node, sourceFile); if (typeArgInfo) { var called = typeArgInfo.called, nTypeArguments = typeArgInfo.nTypeArguments; var invocation = { kind: 1 /* TypeArgs */, called: called }; var argumentsSpan = ts.createTextSpanFromBounds(called.getStart(sourceFile), node.end); - return { kind: 0 /* TypeArguments */, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; + return { isTypeParameterList: true, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; } + return undefined; } - return undefined; + } + function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) { + return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile); + } + function getHighestBinary(b) { + return ts.isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b; + } + function countBinaryExpressionParameters(b) { + return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2; + } + function tryGetParameterInfo(startingToken, _position, sourceFile, checker) { + var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker); + if (!info) + return undefined; + var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var signatures = contextualType.getCallSignatures(); + if (signatures.length !== 1) + return undefined; + var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(contextualType.symbol) }; + return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { + if (startingToken.kind !== 19 /* OpenParenToken */ && startingToken.kind !== 26 /* CommaToken */) + return undefined; + var parent = startingToken.parent; + switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + case 154 /* MethodDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + var info = getArgumentOrParameterListInfo(startingToken, sourceFile); + if (!info) + return undefined; + var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); + return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + case 202 /* BinaryExpression */: { + var highestBinary = getHighestBinary(parent); + var contextualType_1 = checker.getContextualType(highestBinary); + var argumentIndex_1 = startingToken.kind === 19 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; + var argumentCount_1 = countBinaryExpressionParameters(highestBinary); + return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) }; + } + default: + return undefined; + } + } + // The type of a function type node has a symbol at that node, but it's better to use the symbol for a parameter or type alias. + function chooseBetterSymbol(s) { + return s.name === "__type" /* Type */ + ? ts.firstDefined(s.declarations, function (d) { return ts.isFunctionTypeNode(d) ? d.parent.symbol : undefined; }) || s + : s; } function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may @@ -98867,7 +100198,7 @@ var ts; ts.Debug.assertLessThan(argumentIndex, argumentCount); } return { - kind: 2 /* TaggedTemplateArguments */, + isTypeParameterList: false, invocation: { kind: 0 /* Call */, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, @@ -98907,20 +100238,20 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile) { - var _loop_19 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker) { + var _loop_16 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); - var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); + var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker); if (argumentInfo) { return { value: argumentInfo }; } }; for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_7 = _loop_19(n); - if (typeof state_7 === "object") - return state_7.value; + var state_4 = _loop_16(n); + if (typeof state_4 === "object") + return state_4.value; } return undefined; } @@ -98934,101 +100265,194 @@ var ts; return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { - var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; - var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.called; - var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); - var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); - var printer = ts.createPrinter({ removeComments: true }); - var items = candidates.map(function (candidateSignature) { - var signatureHelpParameters; - var prefixDisplayParts = []; - var suffixDisplayParts = []; - if (callTargetDisplayParts) { - ts.addRange(prefixDisplayParts, callTargetDisplayParts); - } - var isVariadic; - if (isTypeParameterList) { - isVariadic = false; // type parameter lists are not variadic - prefixDisplayParts.push(ts.punctuationPart(27 /* LessThanToken */)); - 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) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); - }); - ts.addRange(suffixDisplayParts, parameterParts); - } - else { - isVariadic = candidateSignature.hasRestParameter; - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); - printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); - } - }); - ts.addRange(prefixDisplayParts, typeParameterParts); - prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - signatureHelpParameters = ts.map(candidateSignature.parameters, createSignatureHelpParameterForParameter); - suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); - } - var returnTypeParts = ts.mapToDisplayParts(function (writer) { - writer.writePunctuation(":"); - writer.writeSpace(" "); - var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); - if (predicate) { - typeChecker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); - } - else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); - } - }); - ts.addRange(suffixDisplayParts, returnTypeParts); - return { - isVariadic: isVariadic, - prefixDisplayParts: prefixDisplayParts, - suffixDisplayParts: suffixDisplayParts, - separatorDisplayParts: [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()], - parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment(typeChecker), - tags: candidateSignature.getJsDocTags() - }; - }); + function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { + var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); + var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; + var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var selectedItemIndex = candidates.indexOf(resolvedSignature); ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; - function createSignatureHelpParameterForParameter(parameter) { - var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); - printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); - }); - return { - name: parameter.name, - documentation: parameter.getDocumentationComment(typeChecker), - displayParts: displayParts, - isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) - }; + } + function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { + var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; + var prefixDisplayParts = callTargetDisplayParts.concat(prefix); + var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; + var documentation = candidateSignature.getDocumentationComment(checker); + var tags = candidateSignature.getJsDocTags(); + return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) { + return ts.mapToDisplayParts(function (writer) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = checker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); + } + else { + checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); + } + }); + } + function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; + var printer = ts.createPrinter({ removeComments: true }); + var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var parameterParts = ts.mapToDisplayParts(function (writer) { + var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); + }); + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(27 /* LessThanToken */)], suffix: [ts.punctuationPart(29 /* GreaterThanToken */)].concat(parameterParts) }; + } + function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var isVariadic = candidateSignature.hasRestParameter; + var printer = ts.createPrinter({ removeComments: true }); + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); + } + }); + var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(19 /* OpenParenToken */)]), suffix: [ts.punctuationPart(20 /* CloseParenToken */)] }; + } + function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + } + function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + } + })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + var sourcemappedFileCache; + return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; } - function createSignatureHelpParameterForTypeParameter(typeParameter) { - var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); - }); - return { - name: typeParameter.symbol.name, - documentation: ts.emptyArray, - displayParts: displayParts, - isOptional: false - }; + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); + var comment = sourceMapCommentRegExp.exec(lineText); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!lineText.match(whitespaceOrMapCommentRegExp)) { + break; + } } } - })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + // swallow error + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + // obviously invalid map + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, getProgram(), sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function tryGetOriginalLocation(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); + return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + } + function tryGetGeneratedLocation(info) { + var program = getProgram(); + var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = ts.createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; })(ts || (ts = {})); /* @internal */ var ts; @@ -99036,6 +100460,7 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; + var checker = program.getDiagnosticsProducingTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { @@ -99066,8 +100491,8 @@ var ts; case 194 /* FunctionExpression */: var decl = ts.getDeclarationOfJSInitializer(node); if (decl) { - var symbol_3 = decl.symbol; - if (symbol_3 && (symbol_3.exports && symbol_3.exports.size || symbol_3.members && symbol_3.members.size)) { + var symbol_2 = decl.symbol; + if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); break; } @@ -99095,6 +100520,9 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } + if (ts.isFunctionLikeDeclaration(node)) { + addConvertToAsyncFunctionDiagnostics(node, checker, diags); + } node.forEachChild(check); } } @@ -99135,9 +100563,56 @@ var ts; return undefined; } } + function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { + var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; + if (ts.isAsyncFunction(node) || !node.body || !functionType) { + return; + } + var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); + var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { + return; + } + // collect all the return statements + // check that a property access expression exists in there and that it is a handler + var returnStatements = getReturnStatementsWithPromiseHandlers(node); + if (returnStatements.length > 0) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } + /** @internal */ + function getReturnStatementsWithPromiseHandlers(node) { + var returnStatements = []; + if (ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + else { + visit(node); + } + function visit(child) { + if (ts.isFunctionLike(child)) { + return; + } + if (ts.isReturnStatement(child)) { + ts.forEachChild(child, addHandlers); + } + function addHandlers(returnChild) { + if (isPromiseHandler(returnChild)) { + returnStatements.push(child); + } + } + ts.forEachChild(child, visit); + } + return returnStatements; + } + ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + function isPromiseHandler(node) { + return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && + (node.expression.name.text === "then" || node.expression.name.text === "catch")); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -99855,7 +101330,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_20 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -99874,7 +101349,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_20(opt); + _loop_17(opt); } return options; } @@ -101474,7 +102949,6 @@ var ts; function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); - var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { @@ -101503,17 +102977,20 @@ var ts; var child = nodes[i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } - if (listEndToken !== 0 /* Unknown */) { - if (formattingScanner.isOnToken()) { - var tokenInfo = formattingScanner.readTokenInfo(parent); - // consume the list end token only if it is still belong to the parent - // there might be the case when current token matches end token but does not considered as one - // function (x: function) <-- - // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { - // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); - } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.readTokenInfo(parent); + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } } } @@ -101689,7 +103166,6 @@ var ts; // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; - var parts; if (startLine === endLine) { if (!firstLineIsIndented) { // treat as single line comment @@ -101697,18 +103173,18 @@ var ts; } return; } - else { - parts = []; - var startPos = commentRange.pos; - for (var line = startLine; line < endLine; line++) { - var endOfLine = ts.getEndLinePosition(line, sourceFile); - parts.push({ pos: startPos, end: endOfLine }); - startPos = ts.getStartPositionOfLine(line + 1, sourceFile); - } - if (indentFinalLine) { - parts.push({ pos: startPos, end: commentRange.end }); - } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } + if (parts.length === 0) + return; var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); if (indentation === nonWhitespaceColumnInFirstPart.column) { @@ -102248,7 +103724,13 @@ var ts; getListIfStartEndIsInListRange(node.parent.parameters, start, end); } case 238 /* ClassDeclaration */: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 301 /* JSDocTemplateTag */: { + var typeParameters = node.parent.typeParameters; + return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end); + } case 190 /* NewExpression */: case 189 /* CallExpression */: { var start = node.getStart(sourceFile); @@ -102457,17 +103939,10 @@ var ts; function isControlFlowEndingStatement(kind, parent) { switch (kind) { case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: { - if (parent.kind !== 216 /* Block */) { - return true; - } - var grandParent = parent.parent; - // In a function, we may want to write inner functions after this. - return !(grandParent && grandParent.kind === 194 /* FunctionExpression */ || grandParent.kind === 237 /* FunctionDeclaration */); - } + case 232 /* ThrowStatement */: case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - return true; + return parent.kind !== 216 /* Block */; default: return false; } @@ -102627,7 +104102,7 @@ var ts; return this; }; ChangeTracker.prototype.delete = function (sourceFile, node) { - this.deletedNodes.push({ sourceFile: sourceFile, node: node, }); + this.deletedNodes.push({ sourceFile: sourceFile, node: node }); }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); @@ -103014,15 +104489,20 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_21 = function (sourceFile, node) { + var _loop_18 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { - deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + if (ts.isArray(node)) { + this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); + } + else { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } } }; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_21(sourceFile, node); + _loop_18(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -103072,14 +104552,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_22 = function (i) { + var _loop_19 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_22(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -103385,21 +104865,9 @@ var ts; case 235 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 148 /* TypeParameter */: { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node.parent); - if (typeParameters.length === 1) { - var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; - var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1); - var nextToken = ts.getTokenAtPosition(sourceFile, end); - ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); - ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); - changes.deleteNodeRange(sourceFile, previousToken, nextToken); - } - else { - deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); - } + case 148 /* TypeParameter */: + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - } case 251 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { @@ -103979,6 +105447,442 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertToAsyncFunction"; + var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, + }); + function convertToAsyncFunction(changes, sourceFile, position, checker, context) { + // get the function declaration - returns a promise + var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + if (!functionToConvert) { + return; + } + var synthNamesMap = ts.createMap(); + var originalTypeMap = ts.createMap(); + var allVarNames = []; + var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); + var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + var constIdentifiers = getConstIdentifiers(synthNamesMap); + var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + if (!returnStatements.length) { + return; + } + // add the async keyword + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + function startTransformation(node, nodeToReplace) { + var newNodes = transformExpression(node, transformer, node); + changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); + } + var _loop_20 = function (statement) { + if (ts.isCallExpression(statement)) { + startTransformation(statement, statement); + } + else { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + }; + for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { + var statement = returnStatements_1[_i]; + _loop_20(statement); + } + } + // Returns the identifiers that are never reassigned in the refactor + function getConstIdentifiers(synthNamesMap) { + var constIdentifiers = []; + synthNamesMap.forEach(function (val) { + if (val.numberOfAssignmentsOriginal === 0) { + constIdentifiers.push(val.identifier); + } + }); + return constIdentifiers; + } + /* + Finds all of the expressions of promise type that should not be saved in a variable during the refactor + */ + function getAllPromiseExpressionsToReturn(func, checker) { + if (!func.body) { + return ts.createMap(); + } + var setOfExpressionsToReturn = ts.createMap(); + ts.forEachChild(func.body, function visit(node) { + if (isPromiseReturningExpression(node, checker, "then")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + ts.forEach(node.arguments, visit); + } + else if (isPromiseReturningExpression(node, checker, "catch")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned + ts.forEachChild(node, visit); + } + else if (isPromiseReturningExpression(node, checker)) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // don't recurse here, since we won't refactor any children or arguments of the expression + } + else { + ts.forEachChild(node, visit); + } + }); + return setOfExpressionsToReturn; + } + /* + Returns true if node is a promise returning expression + If name is not undefined, node is a promise returning call of name + */ + function isPromiseReturningExpression(node, checker, name) { + var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); + var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); + return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); + } + function declaredInFile(symbol, sourceFile) { + return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile; + } + /* + Renaming of identifiers may be neccesary as the refactor changes scopes - + This function collects all existing identifier names and names of identifiers that will be created in the refactor. + It then checks for any collisions and renames them through getSynthesizedDeepClone + */ + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { + var identsToRenameMap = ts.createMap(); // key is the symbol id + ts.forEachChild(nodeToRename, function visit(node) { + if (!ts.isIdentifier(node)) { + ts.forEachChild(node, visit); + return; + } + var symbol = checker.getSymbolAtLocation(node); + var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile); + if (symbol && isDefinedInFile) { + var type = checker.getTypeAtLocation(node); + var lastCallSignature = getLastCallSignature(type, checker); + var symbolIdString = ts.getSymbolId(symbol).toString(); + // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) + // Note - the choice of the last call signature is arbitrary + if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { + var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + synthNamesMap.set(symbolIdString, synthName); + allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + } + // we only care about identifiers that are parameters and declarations (don't care about other uses) + else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + // if the identifier name conflicts with a different identifier that we've already seen + if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { + var newName = getNewNameIfConflict(node, allVarNames); + identsToRenameMap.set(symbolIdString, newName.identifier); + synthNamesMap.set(symbolIdString, newName); + allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + } + else { + var identifier = ts.getSynthesizedDeepClone(node); + identsToRenameMap.set(symbolIdString, identifier); + synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); + if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { + allVarNames.push({ identifier: identifier, symbol: symbol }); + } + } + } + } + }); + return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback); + function isExpressionOrCallOnTypePromise(child) { + var node = child.parent; + if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) { + var nodeType = checker.getTypeAtLocation(node); + var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType); + return !!isPromise; + } + return false; + } + function deepCloneCallback(node, clone) { + if (ts.isIdentifier(node)) { + var symbol = checker.getSymbolAtLocation(node); + var symboldIdString = symbol && ts.getSymbolId(symbol).toString(); + var renameInfo = symbol && synthNamesMap.get(symboldIdString); + if (renameInfo) { + var type = checker.getTypeAtLocation(node); + if (type) { + originalType.set(ts.getNodeId(clone).toString(), type); + } + } + } + var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); + if (val !== undefined) { + setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString()); + setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val); + } + } + } + function getNewNameIfConflict(name, allVarNames) { + var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + var numberOfAssignmentsOriginal = 0; + var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); + return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + // dispatch function to recursively build the refactoring + function transformExpression(node, transformer, outermostParent, prevArgName) { + if (!node) { + return []; + } + var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); + var nodeType = originalType || transformer.checker.getTypeAtLocation(node); + if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformThen(node, transformer, outermostParent, prevArgName); + } + else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformCatch(node, transformer, prevArgName); + } + else if (ts.isPropertyAccessExpression(node)) { + return transformExpression(node.expression, transformer, outermostParent, prevArgName); + } + else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformPromiseCall(node, transformer, prevArgName); + } + return []; + } + function transformCatch(node, transformer, prevArgName) { + var func = node.arguments[0]; + var argName = getArgName(func, transformer); + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + /* + If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) + To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap + We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step + */ + if (prevArgName && !shouldReturn) { + prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block + transformer.synthNamesMap.forEach(function (val, key) { + if (val.identifier.text === prevArgName.identifier.text) { + transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + } + }); + // update the constIdentifiers list + if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { + transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + } + } + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); + var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); + var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); + /* + In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) + */ + var varDeclList; + if (prevArgName && !shouldReturn) { + var typeArray = prevArgName.types; + var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var varDecl = [ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)]; + varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); + } + var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); + return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; + } + function transformThen(node, transformer, outermostParent, prevArgName) { + var _a = node.arguments, res = _a[0], rej = _a[1]; + if (!res) { + return transformExpression(node.expression, transformer, outermostParent); + } + var argNameRes = getArgName(res, transformer); + var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); + if (rej) { + var argNameRej = getArgName(rej, transformer); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); + var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); + var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); + return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; + } + else { + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + } + return []; + } + function getFlagOfIdentifier(node, constIdentifiers) { + var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); + return inArr ? 2 /* Const */ : 1 /* Let */; + } + function transformPromiseCall(node, transformer, prevArgName) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call + var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; + var originalNodeParent = node.original ? node.original.parent : node.parent; + if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + } + else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return [ts.createStatement(ts.createAwait(node))]; + } + return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; + } + function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + } + return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + } + function getTransformationBody(func, prevArgName, argName, parent, transformer) { + var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; + var hasArgName = argName && argName.identifier.text.length > 0; + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); + switch (func.kind) { + case 71 /* Identifier */: + if (!hasArgName) + break; + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return ts.createNodeArray([ts.createReturn(synthCall)]); + } + if (!hasPrevArgName) + break; + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); + var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); + var returnType = callSignatures && callSignatures[0].getReturnType(); + var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); + prevArgName.types.push(returnType); + return varDeclOrAssignment; + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + // Arrow functions with block bodies { } will enter this control flow + if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + var refactoredStmts = []; + for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { + refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + } + else { + refactoredStmts.push(statement); + } + } + return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : + removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + } + else { + var funcBody = func.body; + var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); + var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); + if (innerCbBody.length > 0) { + return ts.createNodeArray(innerCbBody); + } + if (hasPrevArgName && !shouldReturn) { + var type_3 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); + var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); + prevArgName.types.push(returnType_1); + return varDeclOrAssignment_1; + } + else { + return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + } + } + break; + } + return ts.createNodeArray([]); + } + function getLastCallSignature(type, checker) { + var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); + return callSignatures && callSignatures[callSignatures.length - 1]; + } + function removeReturns(stmts, prevArgName, constIdentifiers) { + var ret = []; + for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { + var stmt = stmts_1[_i]; + if (ts.isReturnStatement(stmt)) { + if (stmt.expression) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + } + } + else { + ret.push(ts.getSynthesizedDeepClone(stmt)); + } + } + return ts.createNodeArray(ret); + } + function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { + var innerCbBody = []; + for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) { + var stmt = innerRetStmts_1[_i]; + ts.forEachChild(stmt, function visit(node) { + if (ts.isCallExpression(node)) { + var temp = transformExpression(node, transformer, node, prevArgName); + innerCbBody = innerCbBody.concat(temp); + if (innerCbBody.length > 0) { + return; + } + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + return innerCbBody; + } + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + function getArgName(funcNode, transformer) { + var numberOfAssignmentsOriginal = 0; + var types = []; + var name; + if (ts.isFunctionLikeDeclaration(funcNode)) { + if (funcNode.parameters.length > 0) { + var param = funcNode.parameters[0].name; + name = getMapEntryIfExists(param); + } + } + else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { + name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + else if (ts.isIdentifier(funcNode)) { + name = getMapEntryIfExists(funcNode); + } + if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { + return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + return name; + function getMapEntryIfExists(identifier) { + var originalNode = getOriginalNode(identifier); + var symbol = getSymbol(originalNode); + if (!symbol) { + return { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString()); + return mapEntry || { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + function getSymbol(node) { + return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node); + } + function getOriginalNode(node) { + return node.original ? node.original : node; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -104522,6 +106426,8 @@ var ts; var errorCodes = [ ts.Diagnostics.Cannot_find_name_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics.Cannot_find_namespace_0.code, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, @@ -104542,6 +106448,7 @@ var ts; var sourceFile = context.sourceFile, preferences = context.preferences; // Namespace fixes don't conflict, so just build a list. var addToNamespace = []; + var importType = []; // Keys are import clause node IDs. var addToExisting = ts.createMap(); // Keys are module specifiers. @@ -104556,7 +106463,10 @@ var ts; case 0 /* UseNamespace */: addToNamespace.push(fix); break; - case 1 /* AddToExisting */: { + case 1 /* ImportType */: + importType.push(fix); + break; + case 2 /* AddToExisting */: { var importClause = fix.importClause, importKind = fix.importKind; var key = String(ts.getNodeId(importClause)); var entry = addToExisting.get(key); @@ -104572,7 +106482,7 @@ var ts; } break; } - case 2 /* AddNew */: { + case 3 /* AddNew */: { var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; var entry = newImports.get(moduleSpecifier); if (!entry) { @@ -104599,15 +106509,19 @@ var ts; } }); return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var quotePreference = ts.getQuotePreference(sourceFile, preferences); for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { var fix = addToNamespace_1[_i]; addNamespaceQualifier(changes, sourceFile, fix); } + for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { + var fix = importType_1[_a]; + addImportType(changes, sourceFile, fix, quotePreference); + } addToExisting.forEach(function (_a) { var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); }); - var quotePreference = ts.getQuotePreference(sourceFile, preferences); newImports.forEach(function (imports, moduleSpecifier) { addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); }); @@ -104618,8 +106532,9 @@ var ts; var ImportFixKind; (function (ImportFixKind) { ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; - ImportFixKind[ImportFixKind["AddToExisting"] = 1] = "AddToExisting"; - ImportFixKind[ImportFixKind["AddNew"] = 2] = "AddNew"; + ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType"; + ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; })(ImportFixKind || (ImportFixKind = {})); var ImportKind; (function (ImportKind) { @@ -104628,12 +106543,12 @@ var ts; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, allSourceFiles, formatContext, symbolToken, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; - var fix = ts.first(getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences)); + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; } codefix.getImportCompletionAction = getImportCompletionAction; @@ -104648,22 +106563,25 @@ var ts; var exported = _a[_i]; if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ }); + result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); } } }); return result; } - function getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences) { + function isTypeOnlySymbol(s) { + return !(s.flags & 67216319 /* Value */); + } + function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); - var useNamespace = tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker); + var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports); // Don't bother providing an action to add a new import if we can add to an existing one. - var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences); + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences); return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); } - function tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker) { + function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { // It is possible that multiple import statements with the same specifier exist in the file. // e.g. // @@ -104676,13 +106594,13 @@ var ts; // 1. change "member3" to "ns.member3" // 2. add "member3" to the second import statement's import list // and it is up to the user to decide which one fits best. - return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; var namespace = getNamespaceImportName(declaration); if (namespace) { var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, symbolToken: symbolToken }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; } } }); @@ -104697,7 +106615,7 @@ var ts; return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) - ? { kind: 1 /* AddToExisting */, importClause: importClause, importKind: importKind } + ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } : undefined; }); } @@ -104710,27 +106628,31 @@ var ts; return declaration.name; } } - function getExistingImportDeclarations(_a, checker, _b) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var imports = _b.imports; - return ts.mapDefined(imports, function (moduleSpecifier) { + function getExistingImportDeclarations(_a, checker, sourceFile) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + // Can't use an es6 import for a type in JS. + return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } - function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { + function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { + var isJs = ts.isSourceFileJavaScript(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ kind: 2 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); + return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. + return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; + }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences) { + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, exportInfos, host, preferences); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); } function newImportInfoFromExistingSpecifier(_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -104739,13 +106661,13 @@ var ts; : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ ? declaration.moduleReference.expression : undefined; - return expression && ts.isStringLiteral(expression) ? { kind: 2 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; + return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; } function getFixesInfo(context, errorCode, pos) { var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) - : getFixesInfoForNonUMDImport(context, symbolToken); + : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined; return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); } function getFixesInfoForUMDImport(_a, token) { @@ -104756,8 +106678,8 @@ var ts; return undefined; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; - var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()) }]; - var fixes = getFixForImport(exportInfos, symbolName, token, program, sourceFile, host, preferences); + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -104795,21 +106717,18 @@ var ts; } function getFixesInfoForNonUMDImport(_a, symbolToken) { var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; - // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. var checker = program.getTypeChecker(); // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken - && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) ? checker.getJsxNamespace() - : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; - if (!symbolName) - return undefined; + : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */); var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences); + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } @@ -104819,7 +106738,7 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); @@ -104840,7 +106759,6 @@ var ts; return originalSymbolToExportInfos; } function getDefaultExportInfo(defaultExport, moduleSymbol, program) { - var checker = program.getTypeChecker(); var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -104848,12 +106766,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = checker.getAliasedSymbol(defaultExport); - return getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); } else { - var moduleName = moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target); - return moduleName === undefined ? undefined : { symbolForMeaning: defaultExport, name: moduleName }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; } } function getNameForExportDefault(symbol) { @@ -104881,18 +106798,21 @@ var ts; case 0 /* UseNamespace */: addNamespaceQualifier(changes, sourceFile, fix); return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; - case 1 /* AddToExisting */: { + case 1 /* ImportType */: + addImportType(changes, sourceFile, fix, quotePreference); + return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; + case 2 /* AddToExisting */: { var importClause = fix.importClause, importKind = fix.importKind; doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); - return [ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; + return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! } - case 2 /* AddNew */: { + case 3 /* AddNew */: { var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); - return [ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: return ts.Debug.assertNever(fix); @@ -104925,8 +106845,16 @@ var ts; } } function addNamespaceQualifier(changes, sourceFile, _a) { - var namespacePrefix = _a.namespacePrefix, symbolToken = _a.symbolToken; - changes.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken)); + var namespacePrefix = _a.namespacePrefix, position = _a.position; + changes.insertText(sourceFile, position, namespacePrefix + "."); + } + function addImportType(changes, sourceFile, _a, quotePreference) { + var moduleSpecifier = _a.moduleSpecifier, position = _a.position; + changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); + } + function getImportTypePrefix(moduleSpecifier, quotePreference) { + var quote = ts.getQuoteFromPreference(quotePreference); + return "import(" + quote + moduleSpecifier + quote + ")."; } function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; @@ -105015,6 +106943,8 @@ var ts; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, ]; codefix.registerCodeFix({ @@ -105054,7 +106984,7 @@ var ts; var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { - suggestion = checker.getSuggestionForNonexistentModule(node, resolvedSourceFile.symbol); + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); } } else { @@ -105113,16 +107043,16 @@ var ts; var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); if (!info) return undefined; - if (info.kind === InfoKind.enum) { + if (info.kind === 0 /* Enum */) { var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; } - var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); - var addMember = inJs ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic)) : - getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, parentDeclaration, token, makeStatic); + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, fixIds: [fixId], @@ -105130,76 +107060,76 @@ var ts; var program = context.program, preferences = context.preferences; var checker = program.getTypeChecker(); var seen = ts.createMap(); - var classToMembers = new ts.NodeMap(); + var typeDeclToMembers = new ts.NodeMap(); return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { codefix.eachDiagnostic(context, errorCodes, function (diag) { var info = getInfo(diag.file, diag.start, checker); if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { return; } - if (info.kind === InfoKind.enum) { + if (info.kind === 0 /* Enum */) { var token = info.token, parentDeclaration = info.parentDeclaration; addEnumMemberDeclaration(changes, checker, token, parentDeclaration); } else { var parentDeclaration = info.parentDeclaration, token_2 = info.token; - var infos = classToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; }); if (!infos.some(function (i) { return i.token.text === token_2.text; })) infos.push(info); } }); - classToMembers.forEach(function (infos, classDeclaration) { - var superClasses = getAllSuperClasses(classDeclaration, checker); - var _loop_23 = function (info) { + typeDeclToMembers.forEach(function (infos, classDeclaration) { + var supers = getAllSupers(classDeclaration, checker); + var _loop_21 = function (info) { // If some superclass added this property, don't add it again. - if (superClasses.some(function (superClass) { - var superInfos = classToMembers.get(superClass); + if (supers.some(function (superClassOrInterface) { + var superInfos = typeDeclToMembers.get(superClassOrInterface); return !!superInfos && superInfos.some(function (_a) { var token = _a.token; return token.text === info.token.text; }); })) return "continue"; - var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; // Always prefer to add a method declaration if possible. if (call) { - addMethodDeclaration(context, changes, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); } else { - if (inJs) { - addMissingMemberInJs(changes, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic); + if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token.text, makeStatic); } else { var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); - addPropertyDeclaration(changes, classDeclarationSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic); } } }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_23(info); + _loop_21(info); } }); })); }, }); - function getAllSuperClasses(cls, checker) { + function getAllSupers(decl, checker) { var res = []; - while (cls) { - var superElement = ts.getClassExtendsHeritageElement(cls); + while (decl) { + var superElement = ts.getClassExtendsHeritageElement(decl); var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); if (superDecl) { res.push(superDecl); } - cls = superDecl; + decl = superDecl; } return res; } var InfoKind; (function (InfoKind) { - InfoKind[InfoKind["enum"] = 0] = "enum"; - InfoKind[InfoKind["class"] = 1] = "class"; + InfoKind[InfoKind["Enum"] = 0] = "Enum"; + InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface"; })(InfoKind || (InfoKind = {})); function getInfo(tokenSourceFile, tokenPos, checker) { // The identifier of the missing property. eg: @@ -105216,33 +107146,34 @@ var ts; var symbol = leftExpressionType.symbol; if (!symbol || !symbol.declarations) return undefined; - var classDeclaration = ts.find(symbol.declarations, ts.isClassLike); - if (classDeclaration) { - var makeStatic = leftExpressionType.target !== checker.getDeclaredTypeOfSymbol(symbol); - var classDeclarationSourceFile = classDeclaration.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(classDeclarationSourceFile); + // Prefer to change the class instead of the interface if they are merged + var classOrInterface = ts.find(symbol.declarations, ts.isClassLike) || ts.find(symbol.declarations, ts.isInterfaceDeclaration); + if (classOrInterface) { + var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); + var declSourceFile = classOrInterface.getSourceFile(); + var inJs = ts.isSourceFileJavaScript(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); - return { kind: InfoKind.class, token: token, parentDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; + return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); if (enumDeclaration) { - return { kind: InfoKind.enum, token: token, parentDeclaration: enumDeclaration }; + return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration }; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); + function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { if (classDeclaration.kind === 207 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); - changeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization); + changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization); } else { var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); @@ -105250,32 +107181,32 @@ var ts; return; } var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); - changeTracker.insertNodeAtConstructorEnd(classDeclarationSourceFile, classConstructor, propertyInitialization); + changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization); } } function initializePropertyToUndefined(obj, propertyName) { return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); } - function getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic) { + function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) { var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); - var addProp = createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, token.text, typeNode); - return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, token.text, typeNode)]; + var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)]; } function getTypeNode(checker, classDeclaration, token) { var typeNode; if (token.parent.parent.kind === 202 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); // TODO: GH#18217 + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); } - function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } - function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, @@ -105283,10 +107214,10 @@ var ts; /*initializer*/ undefined); var lastProp = getNodeToInsertPropertyAfter(classDeclaration); if (lastProp) { - changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + changeTracker.insertNodeAfter(declSourceFile, lastProp, property); } else { - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property); } } // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. @@ -105300,7 +107231,7 @@ var ts; } return res; } - function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { + function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. var stringTypeNode = ts.createKeywordTypeNode(137 /* StringKeyword */); var indexingParameter = ts.createParameter( @@ -105312,22 +107243,22 @@ var ts; var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(context, changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences); + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); - if (containingMethodDeclaration && containingMethodDeclaration.parent === classDeclaration) { - changeTracker.insertNodeAfter(classDeclarationSourceFile, containingMethodDeclaration, methodDeclaration); + if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { + changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); } else { - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); + changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); } } function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { @@ -105626,6 +107557,7 @@ var ts; var fixName = "unusedIdentifier"; var fixIdPrefix = "unusedIdentifier_prefix"; var fixIdDelete = "unusedIdentifier_delete"; + var fixIdInfer = "unusedIdentifier_infer"; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics._0_is_declared_but_never_used.code, @@ -105633,6 +107565,7 @@ var ts; ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ts.Diagnostics.All_destructured_elements_are_unused.code, ts.Diagnostics.All_variables_are_unused.code, + ts.Diagnostics.All_type_parameters_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -105641,28 +107574,42 @@ var ts; var checker = program.getTypeChecker(); var sourceFiles = program.getSourceFiles(); var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (ts.isJSDocTemplateTag(token)) { + return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; + } + if (token.kind === 27 /* LessThanToken */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); + return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; + } var importDecl = tryGetFullImport(token); if (importDecl) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); - return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])]; } var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); }); if (delDestructure.length) { - return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)]; } var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); if (delVar.length) { - return [codefix.createCodeFixAction(fixName, delVar, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; } var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { - return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); - }); - if (deletion.length) { - var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; - result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); + if (token.kind === 126 /* InferKeyword */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); + var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; + result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); + } + else { + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); + if (deletion.length) { + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + } } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { @@ -105670,7 +107617,7 @@ var ts; } return result; }, - fixIds: [fixIdPrefix, fixIdDelete], + fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program; var checker = program.getTypeChecker(); @@ -105679,27 +107626,47 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, diag.start); switch (context.fixId) { case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); - } + tryPrefixDeclaration(changes, diag.code, sourceFile, token); break; case fixIdDelete: { + if (token.kind === 126 /* InferKeyword */) + break; // Can't delete var importDecl = tryGetFullImport(token); if (importDecl) { changes.delete(sourceFile, importDecl); } + else if (ts.isJSDocTemplateTag(token)) { + changes.delete(sourceFile, token); + } + else if (token.kind === 27 /* LessThanToken */) { + deleteTypeParameters(changes, sourceFile, token); + } else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && !tryDeleteFullVariableStatement(sourceFile, token, changes)) { tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); } break; } + case fixIdInfer: + if (token.kind === 126 /* InferKeyword */) { + changeInferToUnknown(changes, sourceFile, token); + } + break; default: ts.Debug.fail(JSON.stringify(context.fixId)); } }); }, }); + function changeInferToUnknown(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(142 /* UnknownKeyword */)); + } + function createDeleteFix(changes, diag) { + return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); + } + function deleteTypeParameters(changes, sourceFile, token) { + changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters)); + } // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(token) { return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; @@ -105726,13 +107693,19 @@ var ts; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { // Don't offer to prefix a property. - if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) { + if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) + return; + if (token.kind === 126 /* InferKeyword */) { + token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; + } + if (ts.isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); } } function canPrefix(token) { switch (token.parent.kind) { case 149 /* Parameter */: + case 148 /* TypeParameter */: return true; case 235 /* VariableDeclaration */: { var varDecl = token.parent; @@ -105823,69 +107796,54 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, }); - function doChange(changes, sourceFile, start) { + function doChange(changes, sourceFile, start, length) { var token = ts.getTokenAtPosition(sourceFile, start); var statement = ts.findAncestor(token, ts.isStatement); ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; - switch (container.kind) { - case 220 /* IfStatement */: - if (container.elseStatement) { - if (ts.isBlock(statement.parent)) { - changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); - } - else { - changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 220 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; } - break; - } - // falls through - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - changes.delete(sourceFile, container); - break; - default: - if (ts.isBlock(statement.parent)) { - split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); - } - else { - changes.delete(sourceFile, statement); - } + // falls through + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } } - } - function shouldRemove(s) { - // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && - // `var x;` may declare a variable used above - !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); - } - function isPurelyTypeDeclaration(s) { - switch (s.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - return true; - case 242 /* ModuleDeclaration */: - return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; - case 241 /* EnumDeclaration */: - return ts.hasModifier(s, 2048 /* Const */); - default: - return false; + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); } } - function sliceAfter(arr, value) { - var index = arr.indexOf(value); - ts.Debug.assert(index !== -1); - return arr.slice(index); - } - // Calls 'cb' with the start and end of each range where 'pred' is true. - function split(arr, pred, cb) { - ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); }); + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -106219,7 +108177,7 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences) { + function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { @@ -106244,7 +108202,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences)); + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -106760,7 +108718,7 @@ var ts; return; } else { - var indexType = checker.getTypeAtLocation(parent); + var indexType = checker.getTypeAtLocation(parent.argumentExpression); var indexUsageContext = {}; inferTypeFromContext(parent, checker, indexUsageContext); if (indexType.flags & 168 /* NumberLike */) { @@ -106818,10 +108776,10 @@ var ts; } } if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); // TODO: GH#18217 + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); } return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 } @@ -106941,7 +108899,7 @@ var ts; return getImportCodeFixesForExpression(context, node); } function getImportCodeFixesForExpression(context, expr) { - var type = context.program.getTypeChecker().getTypeAtLocation(expr); // TODO: GH#18217 + var type = context.program.getTypeChecker().getTypeAtLocation(expr); if (!(type.symbol && type.symbol.originatingImport)) { return []; } @@ -107523,7 +109481,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_24 = function (element) { + var _loop_22 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -107542,7 +109500,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_24(element); + _loop_22(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -108276,8 +110234,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), // TODO: GH#18217 - scope, 1 /* NoTruncation */); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -108582,7 +110539,7 @@ var ts; return scope.members; } else { - ts.assertTypeIsNever(scope); + ts.assertType(scope); } return ts.emptyArray; } @@ -108704,7 +110661,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { // TODO: GH#18217 + else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -108775,7 +110732,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_25 = function (i) { + var _loop_23 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -108815,7 +110772,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_25(i); + _loop_23(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -108837,7 +110794,7 @@ var ts; function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1 /* Read */; } if (inGenericContext) { - var type = checker.getTypeAtLocation(node); // TODO: GH#18217 + var type = checker.getTypeAtLocation(node); recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { @@ -109365,10 +111322,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_26 = function (sourceFile) { + var _loop_24 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_27 = function (statement) { + var _loop_25 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -109390,12 +111347,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_27(statement); + _loop_25(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_26(sourceFile); + _loop_24(sourceFile); } } function getNamespaceLikeImport(node) { @@ -109510,9 +111467,9 @@ var ts; if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { - var exports_3 = addExport(statement, useEs6Exports); - if (exports_3) - return exports_3; + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; } return statement; }); @@ -109540,7 +111497,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -110071,7 +112028,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 302 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 303 /* LastJSDocNode */; }); return child.kind < 146 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -110141,7 +112098,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(303 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(304 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -110387,8 +112344,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -110871,7 +112828,6 @@ var ts; if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } - var sourcemappedFileCache; function log(message) { if (host.log) { host.log(message); @@ -110879,6 +112835,7 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -110976,7 +112933,7 @@ var ts; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during // the course of whatever called `synchronizeHostData` - sourcemappedFileCache = ts.createSourceFileLikeCache(host); + sourceMapper.clearCache(); // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); @@ -111125,31 +113082,15 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - // Try getting just type at this position and show - switch (node.kind) { - case 71 /* Identifier */: - if (ts.isLabelName(node)) { - // Type here will be 'any', avoid displaying this. - return undefined; - } - // falls through - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 97 /* SuperKeyword */: - // For the identifiers/this/super etc get the type at position - var type_4 = typeChecker.getTypeAtLocation(node); - return type_4 && { - kind: "" /* unknown */, - kindModifiers: "" /* none */, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined - }; - } - return undefined; + var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_4 && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), + documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); @@ -111163,177 +113104,39 @@ var ts; tags: 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); - var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); - if (property) { - return property; - } - } - return checker.getSymbolAtLocation(node); - } - function toLineColumnOffset(fileName, position) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 - return file.getLineAndCharacterOfPosition(position); - } - // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) - var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/; - var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; - var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); - if (!mappedFile) { - return; - } - var starts = ts.getLineStarts(mappedFile); - for (var index = starts.length - 1; index >= 0; index--) { - var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); - var comment = sourceMapCommentRegExp.exec(lineText); - if (comment) { - return comment[1]; - } - // If we see a nonwhitespace/map comment-like line, break, to avoid scanning up the entire file - else if (!lineText.match(whitespaceOrMapCommentRegExp)) { - break; - } - } - } - function convertDocumentToSourceMapper(file, contents, mapFileName) { - var maps; - try { - maps = JSON.parse(contents); - } - catch (_a) { - // swallow error - } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { - // obviously invalid map - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - return file.sourceMapper = ts.sourcemaps.decode({ - readFile: function (s) { return host.readFile(s); }, - fileExists: function (s) { return host.fileExists(s); }, - getCanonicalFileName: getCanonicalFileName, - log: log, - }, mapFileName, maps, program, sourcemappedFileCache); - } - function getSourceMapper(fileName, file) { - if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - if (file.sourceMapper) { - return file.sourceMapper; - } - var mapFileName = scanForSourcemapURL(fileName); - if (mapFileName) { - var match = base64UrlRegExp.exec(mapFileName); - if (match) { - if (match[1]) { - var base64Object = match[1]; - return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); - } - // Not a data URL we can parse, skip it - mapFileName = undefined; - } - } - var possibleMapLocations = []; - if (mapFileName) { - possibleMapLocations.push(mapFileName); - } - possibleMapLocations.push(fileName + ".map"); - for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { - var location = possibleMapLocations_1[_i]; - var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); - if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 - } - } - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - function makeGetTargetOfMappedPosition(extract, create) { - return getTargetOfMappedPosition; - function getTargetOfMappedPosition(input, original) { - if (original === void 0) { original = input; } - var info = extract(input); - if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { - var file = program.getSourceFile(info.fileName); - if (!file) { - var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); - file = sourcemappedFileCache.get(path); - } - if (!file) { - return input; - } - var mapper = getSourceMapper(info.fileName, file); - var newLoc = mapper.getOriginalPosition(info); - if (newLoc === info) - return input; - return getTargetOfMappedPosition(create(newLoc, input, original), original); - } - return input; + function shouldGetType(sourceFile, node, position) { + switch (node.kind) { + case 71 /* Identifier */: + return !ts.isLabelName(node); + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: + // Don't return quickInfo if inside the comment in `a/**/.b` + return !ts.isInComment(sourceFile, position); + case 99 /* ThisKeyword */: + case 176 /* ThisType */: + case 97 /* SuperKeyword */: + return true; + default: + return false; } } - var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({ - containerKind: info.containerKind, - containerName: info.containerName, - fileName: newLoc.fileName, - kind: info.kind, - name: info.name, - textSpan: { - start: newLoc.position, - length: info.textSpan.length - }, - originalFileName: original.fileName, - originalTextSpan: original.textSpan - }); }); - function getTargetOfMappedDeclarationFiles(infos) { - return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); }); - } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position)); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } function getDefinitionAndBoundSpan(fileName, position) { synchronizeHostData(); - var result = ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); - if (!result) - return result; - var mappedDefs = getTargetOfMappedDeclarationFiles(result.definitions); - if (mappedDefs === result.definitions) { - return result; - } - return { - definitions: mappedDefs, - textSpan: result.textSpan - }; + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position)); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } /// Goto implementation - var getTargetOfMappedImplementationLocation = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ - fileName: newLoc.fileName, - kind: info.kind, - displayParts: info.displayParts, - textSpan: { - start: newLoc.position, - length: info.textSpan.length - }, - originalFileName: info.fileName, - originalTextSpan: info.textSpan - }); }); - function getTargetOfMappedImplementationLocations(infos) { - return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); }); - } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedImplementationLocations(ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position)); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -111346,7 +113149,8 @@ var ts; }); }); }); } function getDocumentHighlights(fileName, position, filesToSearch) { - ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === fileName; })); + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); var sourceFile = getValidSourceFile(fileName); @@ -111384,7 +113188,6 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } - /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); @@ -111584,7 +113387,7 @@ var ts; } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } - return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences); + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -111640,10 +113443,15 @@ var ts; return undefined; var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent : ts.isJsxText(token) ? token.parent : undefined; - if (element && !ts.tagNamesAreEquivalent(element.openingElement.tagName, element.closingElement.tagName)) { + if (element && isUnclosedTag(element)) { return { newText: "" }; } } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); @@ -111854,7 +113662,8 @@ var ts; getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, - toLineColumnOffset: toLineColumnOffset + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, }; } ts.createLanguageService = createLanguageService; @@ -111870,7 +113679,7 @@ var ts; function initializeNameTable(sourceFile) { var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteral(node) && literalIsName(node)) { + if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { var text = ts.getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } @@ -111900,6 +113709,11 @@ var ts; */ /* @internal */ function getContainingObjectLiteralElement(node) { + var element = getContainingObjectLiteralElementWorker(node); + return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined; + } + ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; + function getContainingObjectLiteralElementWorker(node) { switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -111914,37 +113728,40 @@ var ts; } return undefined; } - ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; - /* @internal */ - function getPropertySymbolsFromContextualType(typeChecker, node) { - var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); // TODO: GH#18217 - return getPropertySymbolsFromType(contextualType, node.name); // TODO: GH#18217 + function getSymbolAtLocationForQuickInfo(node, checker) { + var object = getContainingObjectLiteralElement(node); + if (object) { + var contextualType = checker.getContextualType(object.parent); + var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); + if (properties && properties.length === 1) { + return ts.first(properties); + } + } + return checker.getSymbolAtLocation(node); } - ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + /** Gets all symbols for one property. Does not get symbols for every property. */ /* @internal */ - function getPropertySymbolsFromType(type, propName) { - var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); - if (name && type) { - var result_7 = []; - var symbol = type.getProperty(name); - if (type.flags & 262144 /* Union */) { - ts.forEach(type.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_7.push(symbol); - } - }); - return result_7; - } - if (symbol) { - result_7.push(symbol); - return result_7; - } + function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + if (!contextualType.isUnion()) { + var symbol = contextualType.getProperty(name); + return symbol ? [symbol] : ts.emptyArray; } - return undefined; + var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); }); + if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { + var symbol = contextualType.getProperty(name); + if (symbol) + return [symbol]; + } + if (discriminatedPropertySymbols.length === 0) { + // Bad discriminant -- do again without discriminating + return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }); + } + return discriminatedPropertySymbols; } - ts.getPropertySymbolsFromType = getPropertySymbolsFromType; + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; function isArgumentOfElementAccessExpression(node) { return node && node.parent && @@ -112712,7 +114529,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { var encoded = this.shimHost.getScriptFileNames(); - return this.files = JSON.parse(encoded); + return JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); @@ -113244,8 +115061,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { - var ref = refs_2[_i]; + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; result.push({ path: ts.normalizeSlashes(ref.fileName), position: ref.pos, @@ -113367,4 +115184,4 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = ts.versionMajorMinor; -//# sourceMappingURL=typescriptServices.js.map \ No newline at end of file +//# sourceMappingURL=typescriptServices.out.js.map \ No newline at end of file diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 133c1e1ca954e..887e98b6f5d90 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -13,9 +13,8 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ - declare namespace ts { - const versionMajorMinor = "3.0"; + const versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ const version: string; } @@ -369,20 +368,21 @@ declare namespace ts { JSDocAugmentsTag = 293, JSDocClassTag = 294, JSDocCallbackTag = 295, - JSDocParameterTag = 296, - JSDocReturnTag = 297, - JSDocThisTag = 298, - JSDocTypeTag = 299, - JSDocTemplateTag = 300, - JSDocTypedefTag = 301, - JSDocPropertyTag = 302, - SyntaxList = 303, - NotEmittedStatement = 304, - PartiallyEmittedExpression = 305, - CommaListExpression = 306, - MergeDeclarationMarker = 307, - EndOfDeclarationMarker = 308, - Count = 309, + JSDocEnumTag = 296, + JSDocParameterTag = 297, + JSDocReturnTag = 298, + JSDocThisTag = 299, + JSDocTypeTag = 300, + JSDocTemplateTag = 301, + JSDocTypedefTag = 302, + JSDocPropertyTag = 303, + SyntaxList = 304, + NotEmittedStatement = 305, + PartiallyEmittedExpression = 306, + CommaListExpression = 307, + MergeDeclarationMarker = 308, + EndOfDeclarationMarker = 309, + Count = 310, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -409,9 +409,9 @@ declare namespace ts { LastBinaryOperator = 70, FirstNode = 146, FirstJSDocNode = 281, - LastJSDocNode = 302, + LastJSDocNode = 303, FirstJSDocTagNode = 292, - LastJSDocTagNode = 302 + LastJSDocTagNode = 303 } enum NodeFlags { None = 0, @@ -480,7 +480,7 @@ declare namespace ts { } 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; + 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 | ExportDeclaration | EndOfFileToken; type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; @@ -546,8 +546,9 @@ declare namespace ts { } interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; - parent: DeclarationWithTypeParameters | InferTypeNode; + parent: DeclarationWithTypeParameterChildren | InferTypeNode; name: Identifier; + /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ constraint?: TypeNode; default?: TypeNode; expression?: Expression; @@ -617,6 +618,7 @@ declare namespace ts { _objectLiteralBrandBrand: any; name?: PropertyName; } + /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { parent: ObjectLiteralExpression; @@ -750,7 +752,7 @@ declare namespace ts { } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; - parent: SignatureDeclaration; + parent: SignatureDeclaration | JSDocTypeExpression; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -1318,7 +1320,8 @@ declare namespace ts { block: Block; } type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; + type DeclarationWithTypeParameters = DeclarationWithTypeParameterChildren | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; + type DeclarationWithTypeParameterChildren = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; @@ -1437,7 +1440,7 @@ declare namespace ts { kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; } - interface ExportDeclaration extends DeclarationStatement { + interface ExportDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ExportDeclaration; parent: SourceFile | ModuleBlock; /** Will not be assigned in the case of `export * from "foo";` */ @@ -1556,12 +1559,17 @@ declare namespace ts { interface JSDocClassTag extends JSDocTag { kind: SyntaxKind.JSDocClassTag; } + interface JSDocEnumTag extends JSDocTag { + kind: SyntaxKind.JSDocEnumTag; + typeExpression?: JSDocTypeExpression; + } interface JSDocThisTag extends JSDocTag { kind: SyntaxKind.JSDocThisTag; typeExpression?: JSDocTypeExpression; } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; + constraint: TypeNode | undefined; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { @@ -1902,7 +1910,7 @@ declare namespace ts { */ getExportSymbolOfSymbol(symbol: Symbol): Symbol; getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; - getTypeAtLocation(node: Node): Type | undefined; + getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; @@ -1934,9 +1942,6 @@ declare namespace ts { getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; - getSuggestionForNonexistentProperty(name: Identifier | string, containingType: Type): string | undefined; - getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; - getSuggestionForNonexistentModule(node: Identifier, target: Symbol): string | undefined; getBaseConstraintOfType(type: Type): Type | undefined; getDefaultFromTypeParameter(type: Type): Type | undefined; /** @@ -2052,6 +2057,7 @@ declare namespace ts { Optional = 16777216, Transient = 33554432, JSContainer = 67108864, + ModuleExports = 134217728, Enum = 384, Variable = 3, Value = 67216319, @@ -2079,8 +2085,6 @@ declare namespace ts { AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, - HasExports = 1955, - HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, ClassMember = 106500 @@ -2110,7 +2114,8 @@ declare namespace ts { Computed = "__computed", Resolving = "__resolving__", ExportEquals = "export=", - Default = "default" + Default = "default", + This = "this" } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -2228,6 +2233,7 @@ declare namespace ts { ReverseMapped = 2048, JsxAttributes = 4096, MarkerType = 8192, + JSLiteral = 16384, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2486,6 +2492,7 @@ declare namespace ts { strictFunctionTypes?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; + stripInternal?: boolean; suppressExcessPropertyErrors?: boolean; suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; @@ -2587,7 +2594,7 @@ declare namespace ts { } interface UpToDateHost { fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date; + getModifiedTime(fileName: string): Date | undefined; getUnchangedTime?(fileName: string): Date | undefined; getLastStatus?(fileName: string): UpToDateStatus | undefined; setLastStatus?(fileName: string, status: UpToDateStatus): void; @@ -2691,7 +2698,7 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date; + getModifiedTime?(fileName: string): Date | undefined; setModifiedTime?(fileName: string, date: Date): void; deleteFile?(fileName: string): void; } @@ -3028,7 +3035,7 @@ declare namespace ts { getCurrentDirectory(): string; getDirectories(path: string): string[]; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - getModifiedTime?(path: string): Date; + getModifiedTime?(path: string): Date | undefined; setModifiedTime?(path: string, time: Date): void; deleteFile?(path: string): void; /** @@ -3186,6 +3193,8 @@ declare namespace ts { * @returns The original parse tree node if found; otherwise, undefined. */ function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier: string): __String; /** * Remove extra underscore from escaped identifier text content. * @@ -3222,6 +3231,8 @@ declare namespace ts { 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 enum tag for the node if present */ + function getJSDocEnumTag(node: Node): JSDocEnumTag | undefined; /** Gets the JSDoc this tag for the node if present */ function getJSDocThisTag(node: Node): JSDocThisTag | undefined; /** Gets the JSDoc return tag for the node if present */ @@ -3243,16 +3254,22 @@ declare namespace ts { */ function getJSDocType(node: Node): TypeNode | undefined; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): ReadonlyArray; /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray; + function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3409,6 +3426,7 @@ declare namespace ts { function isJSDoc(node: Node): node is JSDoc; function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; function isJSDocClassTag(node: Node): node is JSDocClassTag; + function isJSDocEnumTag(node: Node): node is JSDocEnumTag; function isJSDocThisTag(node: Node): node is JSDocThisTag; function isJSDocParameterTag(node: Node): node is JSDocParameterTag; function isJSDocReturnTag(node: Node): node is JSDocReturnTag; @@ -3732,9 +3750,9 @@ declare namespace ts { function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; - function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + /** @deprecated */ function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; - function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + /** @deprecated */ function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; @@ -3743,7 +3761,6 @@ declare namespace ts { function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; 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; - /** @deprecated */ 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; @@ -3759,9 +3776,8 @@ declare namespace ts { function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; - function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + /** @deprecated */ function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; - /** @deprecated */ 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; @@ -4155,10 +4171,14 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; + interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } /** - * Returns the target config filename of a project reference + * Returns the target config filename of a project reference. + * Note: The file might not exist. */ - function resolveProjectReferencePath(host: CompilerHost | UpToDateHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4577,6 +4597,80 @@ declare namespace ts { function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; } +declare namespace ts.server { + type ActionSet = "action::set"; + type ActionInvalidate = "action::invalidate"; + type ActionPackageInstalled = "action::packageInstalled"; + type EventTypesRegistry = "event::typesRegistry"; + type EventBeginInstallTypes = "event::beginInstallTypes"; + type EventEndInstallTypes = "event::endInstallTypes"; + type EventInitializationFailed = "event::initializationFailed"; + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } + interface TypingInstallerResponse { + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + } + interface TypingInstallerRequestWithProjectName { + readonly projectName: string; + } + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { + readonly fileNames: string[]; + readonly projectRootPath: Path; + readonly compilerOptions: CompilerOptions; + readonly typeAcquisition: TypeAcquisition; + readonly unresolvedImports: SortedReadonlyArray; + readonly cachePath?: string; + readonly kind: "discover"; + } + interface CloseProject extends TypingInstallerRequestWithProjectName { + readonly kind: "closeProject"; + } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } + interface PackageInstalledResponse extends ProjectResponse { + readonly kind: ActionPackageInstalled; + readonly success: boolean; + readonly message: string; + } + interface InitializationFailedResponse extends TypingInstallerResponse { + readonly kind: EventInitializationFailed; + readonly message: string; + } + interface ProjectResponse extends TypingInstallerResponse { + readonly projectName: string; + } + interface InvalidateCachedTypings extends ProjectResponse { + readonly kind: ActionInvalidate; + } + interface InstallTypes extends ProjectResponse { + readonly kind: EventBeginInstallTypes | EventEndInstallTypes; + readonly eventId: number; + readonly typingsInstallerVersion: string; + readonly packagesToInstall: ReadonlyArray; + } + interface BeginInstallTypes extends InstallTypes { + readonly kind: EventBeginInstallTypes; + } + interface EndInstallTypes extends InstallTypes { + readonly kind: EventEndInstallTypes; + readonly installSuccess: boolean; + } + interface SetTypings extends ProjectResponse { + readonly typeAcquisition: TypeAcquisition; + readonly compilerOptions: CompilerOptions; + readonly typings: string[]; + readonly unresolvedImports: SortedReadonlyArray; + readonly kind: ActionSet; + } +} declare namespace ts { interface Node { getSourceFile(): SourceFile; @@ -5581,4 +5675,3 @@ declare namespace ts { */ function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions): TransformationResult; } -//# sourceMappingURL=typescriptServices.d.ts.map \ No newline at end of file diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 4785ced00f304..78365f95075b7 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -13,7 +13,6 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ - "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { @@ -74,7 +73,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.0"; + ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1685,6 +1684,9 @@ var ts; if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { var candidateNameLowerCase = candidateName.toLowerCase(); if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } return candidate; } if (justCheckExactMatches) { @@ -1895,8 +1897,8 @@ var ts; return function (arg) { return f(arg) || g(arg); }; } ts.or = or; - function assertTypeIsNever(_) { } // tslint:disable-line no-empty - ts.assertTypeIsNever = assertTypeIsNever; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -2358,23 +2360,24 @@ var ts; SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 296] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 297] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 298] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 299] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 300] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 301] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 302] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 303] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 304] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 305] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 306] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 307] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 308] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 309] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -2402,9 +2405,9 @@ var ts; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 302] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 302] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -2732,6 +2735,7 @@ var ts; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; @@ -2765,8 +2769,6 @@ var ts; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasExports"] = 1955] = "HasExports"; - SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; @@ -2820,6 +2822,7 @@ var ts; InternalSymbolName["Resolving"] = "__resolving__"; InternalSymbolName["ExportEquals"] = "export="; InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); /* @internal */ var NodeCheckFlags; @@ -2876,7 +2879,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["UnionOfUnitTypes"] = 67108864] = "UnionOfUnitTypes"; + TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2919,7 +2922,7 @@ var ts; TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotUnit"] = 16749629] = "NotUnit"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2953,6 +2956,7 @@ var ts; ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -3810,52 +3814,80 @@ var ts; */ /*@internal*/ function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); return createDirectoryWatcher; /** * Create the directory watcher for the dirPath. */ function createDirectoryWatcher(dirName, callback) { - var watcher = host.watchDirectory(dirName, function (fileName) { - // Call the actual callback - callback(fileName); - // Iterate through existing children and update the watches if needed - updateChildWatches(result, callback); - }); - var result = { - close: function () { - watcher.close(); - result.childWatches.forEach(ts.closeFileWatcher); - result = undefined; - }, + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { dirName: dirName, - childWatches: ts.emptyArray + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } }; - updateChildWatches(result, callback); - return result; } - function updateChildWatches(watcher, callback) { + function updateChildWatches(dirName, dirPath) { // Iterate through existing children and update the watches if needed - if (watcher) { - watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); } } /** * Watch the directories in the parentDir */ - function watchChildDirectories(parentDir, existingChildWatches, callback) { + function watchChildDirectories(parentDir, existingChildWatches) { var newChildWatches; ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch - return host.filePathComparer(childFullName, host.realpath(childFullName)) === 0 /* EqualTo */ ? childFullName : undefined; - }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); return newChildWatches || ts.emptyArray; /** * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName) { - var result = createDirectoryWatcher(childName, callback); + var result = createDirectoryWatcher(childName); addChildDirectoryWatcher(result); } /** @@ -3882,7 +3914,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; - // TODO: this is used as if it's certainly defined in many places. + // TODO: GH#18217 this is used as if it's certainly defined in many places. ts.sys = (function () { // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual // byte order mark from the specified encoding. Using any other byte order mark does @@ -3991,18 +4023,17 @@ var ts; process.stdout._handle.setBlocking(true); } }, - base64decode: Buffer.from ? function (input) { - return Buffer.from(input, "base64").toString("utf8"); - } : function (input) { - return new Buffer(input, "base64").toString("utf8"); - }, - base64encode: Buffer.from ? function (input) { - return Buffer.from(input).toString("base64"); - } : function (input) { - return new Buffer(input).toString("base64"); - } + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, }; return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } function isFileSystemCaseSensitive() { // win32\win64 are case insensitive platforms if (platform === "win32" || platform === "win64") { @@ -4055,7 +4086,7 @@ var ts; createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : watchDirectoryUsingFsWatch; var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ - filePathComparer: ts.getStringComparer(!useCaseSensitiveFileNames), + useCaseSensitiveFileNames: useCaseSensitiveFileNames, directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, watchDirectory: watchDirectory, @@ -4065,8 +4096,7 @@ var ts; if (recursive) { return watchDirectoryRecursively(directoryName, callback); } - watchDirectory(directoryName, callback); - return undefined; // TODO: GH#18217 + return watchDirectory(directoryName, callback); }; } function createNonPollingWatchFile() { @@ -4749,6 +4779,8 @@ var ts; Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4801,7 +4833,7 @@ var ts; Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), - Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), @@ -5017,6 +5049,9 @@ var ts; Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), 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."), @@ -5103,8 +5138,11 @@ var ts; Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), - _0_was_declared_here: diag(2728, ts.DiagnosticCategory.Error, "_0_was_declared_here_2728", "'{0}' was declared here."), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), 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}'."), @@ -5218,6 +5256,7 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5408,6 +5447,7 @@ var ts; Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5467,12 +5507,14 @@ var ts; Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), - Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Error, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{0}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5502,6 +5544,7 @@ var ts; Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), 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."), @@ -5532,6 +5575,7 @@ var ts; Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), @@ -5542,6 +5586,8 @@ var ts; Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5559,6 +5605,10 @@ var ts; Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), 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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5621,6 +5671,8 @@ var ts; Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), }; })(ts || (ts = {})); var ts; @@ -7374,6 +7426,7 @@ var ts; } function scanJSDocToken() { startPos = tokenPos = pos; + tokenFlags = 0; if (pos >= end) { return token = 1 /* EndOfFileToken */; } @@ -7392,6 +7445,7 @@ var ts; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: return token = 39 /* AsteriskToken */; @@ -7526,6 +7580,7 @@ var ts; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -7634,6 +7689,19 @@ var ts; return undefined; } ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; function forEachEntry(map, callback) { var _a; var iterator = map.entries(); @@ -7857,26 +7925,22 @@ var ts; } ts.nodeIsPresent = nodeIsPresent; /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. + * Prepends statements to an array while taking care of prologue directives. */ - function prependStatements(to, from) { + function addStatementsAfterPrologue(to, from) { if (from === undefined || from.length === 0) return to; - if (to === undefined) - return from.slice(); - var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); - to.unshift.apply(to, from); - if (prologue) { - to.unshift(prologue); + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } } + to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.prependStatements = prependStatements; + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; /** * Determine if the given comment is a triple-slash * @@ -7919,7 +7983,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 303 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8007,11 +8071,6 @@ var ts; return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; - // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' - function escapeLeadingUnderscores(identifier) { - return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); - } - ts.escapeLeadingUnderscores = escapeLeadingUnderscores; // Make an identifier from an external module name by extracting the string after the last "/" and replacing // all non-alphanumeric characters with underscores function makeIdentifierFromModuleName(moduleName) { @@ -8086,6 +8145,10 @@ var ts; return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -8116,6 +8179,18 @@ var ts; } ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 291 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { case 158 /* CallSignature */: case 159 /* ConstructSignature */: @@ -8128,7 +8203,7 @@ var ts; case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: case 240 /* TypeAliasDeclaration */: - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 155 /* Constructor */: @@ -8136,16 +8211,13 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: - case 291 /* JSDocSignature */: return true; default: - ts.assertTypeIsNever(node); + ts.assertType(node); return false; } } - ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { case 247 /* ImportDeclaration */: @@ -8200,11 +8272,11 @@ var ts; return name.escapedText; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return escapeLeadingUnderscores(name.text); + return ts.escapeLeadingUnderscores(name.text); case 147 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } ts.getTextOfPropertyName = getTextOfPropertyName; @@ -8353,9 +8425,7 @@ var ts; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { - return n.kind === 181 /* ImportType */ && - n.argument.kind === 180 /* LiteralType */ && - ts.isStringLiteral(n.argument.literal); + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { @@ -8444,6 +8514,8 @@ var ts; return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case 148 /* TypeParameter */: return node === parent.constraint; + case 301 /* JSDocTemplateTag */: + return node === parent.constraint; case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: case 149 /* Parameter */: @@ -9043,6 +9115,8 @@ var ts; return true; case 209 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 274 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); } @@ -9113,12 +9187,15 @@ var ts; } ts.isStringDoubleQuoted = isStringDoubleQuoted; function getDeclarationOfJSInitializer(node) { - if (!isInJavaScriptFile(node) || !node.parent) { + if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + return undefined; + } name = node.parent.name; decl = node.parent; } @@ -9276,8 +9353,12 @@ var ts; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder function getSpecialPropertyAssignmentKind(expr) { - if (!isInJavaScriptFile(expr) || - expr.operatorToken.kind !== 58 /* EqualsToken */ || + var special = getSpecialPropertyAssignmentKindWorker(expr); + return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getSpecialPropertyAssignmentKindWorker(expr) { + if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } @@ -9288,7 +9369,6 @@ var ts; } return getSpecialPropertyAccessKind(lhs); } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getSpecialPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; @@ -9336,6 +9416,14 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); } @@ -9412,7 +9500,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 301 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9700,7 +9788,10 @@ var ts; } else { var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + return ts.isBinaryExpression(binExp) && + getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name; } } default: @@ -9903,12 +9994,10 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isStringOrNumericLiteral(node) { - var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 8 /* NumericLiteral */; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); } - ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; /** * A declaration has a dynamic name if both of the following are true: * 1. The declaration has a computed property name @@ -9923,7 +10012,7 @@ var ts; ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { return name.kind === 147 /* ComputedPropertyName */ && - !isStringOrNumericLiteral(name.expression) && + !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -9937,22 +10026,24 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 /* Identifier */) { - return name.escapedText; - } - if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(name.text); - } - if (name.kind === 147 /* ComputedPropertyName */) { - var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(nameExpression.text); - } + switch (name.kind) { + case 71 /* Identifier */: + return name.escapedText; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 147 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); } - return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { @@ -9972,7 +10063,7 @@ var ts; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : escapeLeadingUnderscores(node.text); + return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -10093,7 +10184,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return 0; case 206 /* SpreadElement */: return 1; @@ -10471,27 +10562,30 @@ var ts; return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; - function getOwnEmitOutputFilePath(sourceFile, host, extension) { + function getOwnEmitOutputFilePath(fileName, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; if (compilerOptions.outDir) { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); } else { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); } return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; - function getDeclarationEmitOutputFilePath(sourceFile, host) { - var options = host.getCompilerOptions(); + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } - ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; /** * Gets the source files that are expected to have an emit output. * @@ -10523,14 +10617,17 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - var commonSourceDirectory = host.getCommonSourceDirectory(); - var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } - ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); @@ -10603,7 +10700,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 156 /* GetAccessor */ || member.kind === 157 /* SetAccessor */) + if (ts.isAccessor(member) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -10637,7 +10734,10 @@ var ts; * parsed in a JavaScript file, gets the type annotation from JSDoc. */ function getEffectiveTypeAnnotationNode(node) { - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); + var type = node.type; + if (type || !isInJavaScriptFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; function getTypeAnnotationNode(node) { @@ -10649,27 +10749,11 @@ var ts; * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { - if (ts.isJSDocSignature(node)) { - return node.type && node.type.typeExpression && node.type.typeExpression.type; - } - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - /** - * Gets the effective type parameters. If the node was parsed in a - * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. - */ - function getEffectiveTypeParameterDeclarations(node) { - if (ts.isJSDocSignature(node)) { - return ts.emptyArray; - } - if (isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); - return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); - } - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); - } - ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); } @@ -11436,7 +11520,9 @@ var ts; return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; case 202 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; - return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); default: @@ -11966,6 +12052,11 @@ var ts; return undefined; } ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; /** * Remove extra underscore from escaped identifier text content. * @@ -12051,8 +12142,8 @@ var ts; switch (declaration.kind) { case 71 /* Identifier */: return declaration; - case 302 /* JSDocPropertyTag */: - case 296 /* JSDocParameterTag */: { + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: { var name = declaration.name; if (name.kind === 146 /* QualifiedName */) { return name.right; @@ -12071,7 +12162,7 @@ var ts; return undefined; } } - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); case 252 /* ExportAssignment */: { var expression = declaration.expression; @@ -12156,6 +12247,11 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; /** Gets the JSDoc this tag for the node if present */ function getJSDocThisTag(node) { return getFirstJSDocTag(node, ts.isJSDocThisTag); @@ -12201,14 +12297,27 @@ var ts; } ts.getJSDocType = getJSDocType; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node) { var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } } ts.getJSDocReturnType = getJSDocReturnType; /** Get all JSDoc tags related to a node, including those on parent nodes. */ @@ -12232,6 +12341,28 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -12469,7 +12600,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 305 /* PartiallyEmittedExpression */) { + while (node.kind === 306 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -12872,36 +13003,40 @@ var ts; return node.kind === 294 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 296 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 298 /* JSDocThisTag */; + return node.kind === 299 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 296 /* JSDocParameterTag */; + return node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 297 /* JSDocReturnTag */; + return node.kind === 298 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 299 /* JSDocTypeTag */; + return node.kind === 300 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 300 /* JSDocTemplateTag */; + return node.kind === 301 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 301 /* JSDocTypedefTag */; + return node.kind === 302 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 302 /* JSDocPropertyTag */; + return node.kind === 303 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 302 /* JSDocPropertyTag */ || node.kind === 296 /* JSDocParameterTag */; + return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { @@ -12924,7 +13059,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 303 /* SyntaxList */; + return n.kind === 304 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13389,8 +13524,8 @@ var ts; case 206 /* SpreadElement */: case 210 /* AsExpression */: case 208 /* OmittedExpression */: - case 306 /* CommaListExpression */: - case 305 /* PartiallyEmittedExpression */: + case 307 /* CommaListExpression */: + case 306 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13404,12 +13539,12 @@ var ts; ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 305 /* PartiallyEmittedExpression */; + return node.kind === 306 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 304 /* NotEmittedStatement */; + return node.kind === 305 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13520,9 +13655,9 @@ var ts; || kind === 240 /* TypeAliasDeclaration */ || kind === 148 /* TypeParameter */ || kind === 235 /* VariableDeclaration */ - || kind === 301 /* JSDocTypedefTag */ + || kind === 302 /* JSDocTypedefTag */ || kind === 295 /* JSDocCallbackTag */ - || kind === 302 /* JSDocPropertyTag */; + || kind === 303 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { return kind === 237 /* FunctionDeclaration */ @@ -13557,14 +13692,14 @@ var ts; || kind === 217 /* VariableStatement */ || kind === 222 /* WhileStatement */ || kind === 229 /* WithStatement */ - || kind === 304 /* NotEmittedStatement */ - || kind === 308 /* EndOfDeclarationMarker */ - || kind === 307 /* MergeDeclarationMarker */; + || kind === 305 /* NotEmittedStatement */ + || kind === 309 /* EndOfDeclarationMarker */ + || kind === 308 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 300 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -13659,7 +13794,7 @@ var ts; /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 302 /* LastJSDocNode */; + return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ @@ -13670,7 +13805,7 @@ var ts; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 302 /* LastJSDocTagNode */; + return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -13695,45 +13830,6 @@ var ts; return !!node.type; } ts.hasType = hasType; - /* True if the node could have a type node a `.type` */ - /* @internal */ - function couldHaveType(node) { - switch (node.kind) { - case 149 /* Parameter */: - case 151 /* PropertySignature */: - case 152 /* PropertyDeclaration */: - case 153 /* MethodSignature */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 175 /* ParenthesizedType */: - case 177 /* TypeOperator */: - case 179 /* MappedType */: - case 192 /* TypeAssertionExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 210 /* AsExpression */: - case 235 /* VariableDeclaration */: - case 237 /* FunctionDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 281 /* JSDocTypeExpression */: - case 284 /* JSDocNullableType */: - case 285 /* JSDocNonNullableType */: - case 286 /* JSDocOptionalType */: - case 287 /* JSDocFunctionType */: - case 288 /* JSDocVariadicType */: - return true; - } - return false; - } - ts.couldHaveType = couldHaveType; /** True if has initializer node attached to it. */ /* @internal */ function hasInitializer(node) { @@ -13747,18 +13843,7 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - switch (node.kind) { - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return true; - default: - return false; - } + return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ @@ -14016,7 +14101,7 @@ var ts; } ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { - return !!(options.declaration && options.declarationMap); + return !!(getEmitDeclarations(options) && options.declarationMap); } ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { @@ -14036,6 +14121,14 @@ var ts; return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + if (oldOptions === newOptions) { + return false; + } + return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || + (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14200,6 +14293,12 @@ var ts; return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); } ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; function isUrl(path) { return getEncodedRootLength(path) < 0; } @@ -15052,6 +15151,100 @@ var ts; return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); } ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; })(ts || (ts = {})); var ts; (function (ts) { @@ -15469,7 +15662,7 @@ var ts; return visitNode(cbNode, node.expression); case 256 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 258 /* JsxElement */: return visitNode(cbNode, node.openingElement) || @@ -15509,8 +15702,8 @@ var ts; visitNode(cbNode, node.type); case 289 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15519,15 +15712,15 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 297 /* JSDocReturnTag */: + case 298 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); case 293 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 300 /* JSDocTemplateTag */: - return visitNodes(cbNode, cbNodes, node.typeParameters); - case 301 /* JSDocTypedefTag */: + case 301 /* JSDocTemplateTag */: + return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); + case 302 /* JSDocTypedefTag */: if (node.typeExpression && node.typeExpression.kind === 281 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || @@ -15540,13 +15733,15 @@ var ts; case 295 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 298 /* JSDocThisTag */: + case 299 /* JSDocThisTag */: + return visitNode(cbNode, node.typeExpression); + case 296 /* JSDocEnumTag */: return visitNode(cbNode, node.typeExpression); case 291 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || + ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); case 290 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { @@ -15556,7 +15751,7 @@ var ts; } } return; - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -16405,7 +16600,7 @@ var ts; return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); @@ -16428,7 +16623,7 @@ var ts; return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: if (token() === 26 /* CommaToken */) { @@ -16438,13 +16633,15 @@ var ts; case 11 /* ArgumentExpressions */: return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: - return isStartOfParameter(); - case 19 /* TypeArguments */: - case 20 /* TupleElementTypes */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: return token() === 26 /* CommaToken */ || isStartOfType(); - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return isHeritageClause(); - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; @@ -16509,7 +16706,7 @@ var ts; case 6 /* EnumMembers */: case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return token() === 18 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; @@ -16517,24 +16714,25 @@ var ts; return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: return token() === 22 /* CloseBracketToken */; + case 17 /* JSDocParameters */: case 16 /* Parameters */: - case 17 /* RestProperties */: + case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token return token() !== 26 /* CommaToken */; - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; case 13 /* JsxAttributes */: return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; @@ -16567,7 +16765,7 @@ var ts; } // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 23 /* Count */; kind++) { + for (var kind = 0; kind < 24 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; @@ -16679,24 +16877,25 @@ var ts; return isReusableTypeMember(node); case 8 /* VariableDeclarations */: return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -16704,7 +16903,7 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. @@ -16854,7 +17053,7 @@ var ts; case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected; case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; - case 17 /* RestProperties */: // fallthrough + case 18 /* RestProperties */: // fallthrough case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; @@ -16865,12 +17064,13 @@ var ts; case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected; case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; + case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected; case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 18 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; - case 19 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 20 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; - case 21 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; - case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; + case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; + case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; + case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` @@ -17070,7 +17270,7 @@ var ts; var node = createNode(162 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } return finishNode(node); } @@ -17168,7 +17368,7 @@ var ts; } function parseJSDocType() { var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); - var type = parseType(); + var type = parseTypeOrTypePredicate(); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -17214,7 +17414,7 @@ var ts; } function parseTypeParameters() { if (token() === 27 /* LessThanToken */) { - return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } } function parseParameterType() { @@ -17223,12 +17423,12 @@ var ts; } return undefined; } - function isStartOfParameter() { + function isStartOfParameter(isJSDocParameter) { return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 /* AtToken */ || - isStartOfType(/*inStartOfParameter*/ true); + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { var node = createNodeWithJSDoc(149 /* Parameter */); @@ -17314,7 +17514,9 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1 /* Yield */)); setAwaitContext(!!(flags & 2 /* Await */)); - signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return parseExpected(20 /* CloseParenToken */); @@ -17552,7 +17754,7 @@ var ts; } function parseTupleType() { var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { @@ -17705,6 +17907,8 @@ var ts; case 126 /* InferKeyword */: case 91 /* ImportKeyword */: return true; + case 89 /* FunctionKeyword */: + return !inStartOfParameter; case 38 /* MinusToken */: return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19 /* OpenParenToken */: @@ -17717,7 +17921,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); @@ -18211,8 +18415,9 @@ var ts; return 1 /* True */; } // If we had "(" followed by something that's not an identifier, - // then this definitely doesn't look like a lambda. - if (!isIdentifier()) { + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 99 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { @@ -19047,7 +19252,7 @@ var ts; } else { var argument = allowInAnd(parseExpression); - if (ts.isStringOrNumericLiteral(argument)) { + if (ts.isStringOrNumericLiteralLike(argument)) { argument.text = internIdentifier(argument.text); } indexedAccess.argumentExpression = argument; @@ -19118,7 +19323,7 @@ var ts; if (!parseOptional(27 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; @@ -20270,7 +20475,7 @@ var ts; // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } if (isHeritageClause()) { - return parseList(21 /* HeritageClauses */, parseHeritageClause); + return parseList(22 /* HeritageClauses */, parseHeritageClause); } return undefined; } @@ -20291,7 +20496,7 @@ var ts; } function tryParseTypeArguments() { return token() === 27 /* LessThanToken */ - ? parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) : undefined; } function isHeritageClause() { @@ -20517,7 +20722,7 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { @@ -20631,13 +20836,14 @@ var ts; ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; - ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; // Number of parsing contexts + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -20754,7 +20960,7 @@ var ts; switch (token()) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -20814,7 +21020,7 @@ var ts; nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return createJSDocComment(); }); function removeLeadingNewlines(comments) { @@ -20822,8 +21028,8 @@ var ts; comments.shift(); } } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { comments.pop(); } } @@ -20855,13 +21061,30 @@ var ts; nextJSDocToken(); } } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 39 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } function parseTag(indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": @@ -20875,6 +21098,9 @@ var ts; case "this": tag = parseThisTag(atToken, tagName); break; + case "enum": + tag = parseEnumTag(atToken, tagName); + break; case "arg": case "argument": case "param": @@ -20972,7 +21198,7 @@ var ts; tok = nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { @@ -20995,7 +21221,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespace(); + skipWhitespaceOrAsterisk(); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -21029,15 +21255,15 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespace(); + skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(302 /* JSDocPropertyTag */, atToken.pos) : - createNode(296 /* JSDocParameterTag */, atToken.pos); + createNode(303 /* JSDocPropertyTag */, atToken.pos) : + createNode(297 /* JSDocParameterTag */, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -21063,7 +21289,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) { + if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } } @@ -21079,20 +21305,20 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 297 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(297 /* JSDocReturnTag */, atToken.pos); + var result = createNode(298 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 299 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(299 /* JSDocTypeTag */, atToken.pos); + var result = createNode(300 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); @@ -21133,7 +21359,15 @@ var ts; return finishNode(tag); } function parseThisTag(atToken, tagName) { - var tag = createNode(298 /* JSDocThisTag */, atToken.pos); + var tag = createNode(299 /* JSDocThisTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(atToken, tagName) { + var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); @@ -21143,7 +21377,7 @@ var ts; function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(301 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); @@ -21156,12 +21390,12 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = scanner.getStartPos(); + var start_3 = atToken.pos; while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 299 /* JSDocTypeTag */) { + if (child.kind === 300 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21224,7 +21458,7 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(57 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 297 /* JSDocReturnTag */) { + if (tag && tag.kind === 298 /* JSDocReturnTag */) { return tag; } } @@ -21269,7 +21503,7 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) && + if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -21338,16 +21572,14 @@ var ts; skipWhitespace(); var typeParameter = createNode(148 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); - skipWhitespace(); finishNode(typeParameter); + skipWhitespace(); typeParameters.push(typeParameter); } while (parseOptionalJsdoc(26 /* CommaToken */)); - if (constraint) { - ts.first(typeParameters).constraint = constraint.type; - } - var result = createNode(300 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; + result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); return result; @@ -21873,9 +22105,11 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + ts.isDeclarationFileName = isDeclarationFileName; /*@internal*/ function processCommentPragmas(context, sourceText) { var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); @@ -22419,13 +22653,15 @@ var ts; { name: "noImplicitAny", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type }, { name: "strictNullChecks", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks @@ -22433,6 +22669,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types @@ -22440,6 +22677,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes @@ -22447,6 +22685,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, @@ -22454,6 +22693,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file @@ -22462,6 +22702,7 @@ var ts; { name: "noUnusedLocals", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_locals, @@ -22469,6 +22710,7 @@ var ts; { name: "noUnusedParameters", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_parameters, @@ -22476,6 +22718,7 @@ var ts; { name: "noImplicitReturns", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value @@ -22483,6 +22726,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement @@ -22553,12 +22797,14 @@ var ts; { name: "allowSyntheticDefaultImports", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, { name: "esModuleInterop", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports @@ -22734,6 +22980,7 @@ var ts; { name: "noImplicitUseStrict", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output }, @@ -22772,24 +23019,28 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels }, { name: "allowUnreachableCode", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code }, { name: "suppressExcessPropertyErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, }, { name: "suppressImplicitAnyIndexErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, @@ -22808,6 +23059,7 @@ var ts; { name: "noStrictGenericChecks", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, }, @@ -23329,9 +23581,10 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); - var option = knownOptions ? knownOptions.get(keyText) : undefined; - if (extraKeyDiagnosticMessage && !option) { + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); @@ -24406,9 +24659,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -24637,9 +24890,7 @@ var ts; return perFolderCache; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; // TODO: GH#18217 - } + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { perModuleNameCache = createPerModuleNameCache(); @@ -24671,41 +24922,45 @@ var ts; return; } directoryPathMap.set(path, result); - var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); // find common prefix between directory and resolved file name - // this common prefix should be the shorted path that has the same resolution + // this common prefix should be the shortest path that has the same resolution // directory: /a/b/c/d/e // resolvedFileName: /a/b/foo.d.ts - var commonPrefix = getCommonPrefix(path, resolvedFileName); + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); var current = path; - while (true) { + while (current !== commonPrefix) { var parent = ts.getDirectoryPath(current); if (parent === current || directoryPathMap.has(parent)) { break; } directoryPathMap.set(parent, result); current = parent; - if (current === commonPrefix) { - break; - } } } function getCommonPrefix(directory, resolution) { - if (resolution === undefined) { - return undefined; - } var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); // find first position where directory and resolution differs var i = 0; - while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { i++; } - // find last directory separator before position i - var sep = directory.lastIndexOf(ts.directorySeparator, i); - if (sep < 0) { + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { return undefined; } - return directory.substr(0, sep); + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { + return undefined; + } + return directory.substr(0, Math.max(sep, rootLength)); } } } @@ -24754,10 +25009,9 @@ var ts; } if (perFolderCache) { perFolderCache.set(moduleName, result); - // put result in per-module name cache - var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); - if (perModuleNameCache) { - perModuleNameCache.set(containingDirectory, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); } } } @@ -24982,15 +25236,15 @@ var ts; tryResolve(Extensions.JavaScript) || (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { @@ -25000,17 +25254,13 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - var originalPath = void 0; - if (!compilerOptions.preserveSymlinks && resolvedValue) { - originalPath = resolvedValue.path; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - if (path === originalPath) { - originalPath = undefined; - } - resolvedValue = __assign({}, resolvedValue, { path: path }); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -25063,7 +25313,8 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } - var nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -25077,11 +25328,11 @@ var ts; */ function parseNodeModuleFromPath(resolved) { var path = ts.normalizePath(resolved.path); - var idx = path.lastIndexOf(nodeModulesPathPart); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; } - var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); @@ -25424,7 +25675,7 @@ var ts; trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -25434,17 +25685,17 @@ var ts; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*originalPath*/ undefined, /*isExternalLibraryImport*/ false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -25479,7 +25730,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*originalPath*/ undefined, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -25687,10 +25938,10 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; symbol.declarations = ts.append(symbol.declarations, node); - if (symbolFlags & 1955 /* HasExports */ && !symbol.exports) { + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } - if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } if (symbolFlags & 67216319 /* Value */) { @@ -25717,7 +25968,7 @@ var ts; if (name.kind === 147 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression)) { + if (ts.isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -25762,7 +26013,7 @@ var ts; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); // TODO: GH#18217 + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); } /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @@ -25833,8 +26084,10 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; } if (symbol.declarations && symbol.declarations.length) { // If the current node is a default export of some sort, then check if @@ -25842,6 +26095,7 @@ var ts; // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } else { // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. @@ -25851,13 +26105,15 @@ var ts; if (symbol.declarations && symbol.declarations.length && (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } } } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); symbol = createSymbol(0 /* None */, name); } } @@ -26128,7 +26384,7 @@ var ts; case 189 /* CallExpression */: bindCallExpressionFlow(node); break; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; @@ -26153,6 +26409,7 @@ var ts; case 71 /* Identifier */: case 99 /* ThisKeyword */: case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return isNarrowableReference(expr); case 189 /* CallExpression */: return hasNarrowableArgument(expr); @@ -26166,10 +26423,11 @@ var ts; return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || - expr.kind === 99 /* ThisKeyword */ || - expr.kind === 97 /* SuperKeyword */ || - expr.kind === 187 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -26605,7 +26863,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -26894,7 +27152,7 @@ var ts; case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: case 287 /* JSDocFunctionType */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: case 240 /* TypeAliasDeclaration */: case 179 /* MappedType */: @@ -27232,13 +27490,26 @@ var ts; errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } - function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); if (isError) { file.bindDiagnostics.push(diag); } @@ -27358,12 +27629,19 @@ var ts; } return checkStrictModeIdentifier(node); case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } + if (ts.isInJavaScriptFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(container, "module")) { + declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + } break; case 202 /* BinaryExpression */: var specialKind = ts.getSpecialPropertyAssignmentKind(node); @@ -27405,6 +27683,8 @@ var ts; return checkStrictModePrefixUnaryExpression(node); case 229 /* WithStatement */: return checkStrictModeWithStatement(node); + case 231 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); case 176 /* ThisType */: seenThisKeyword = true; return; @@ -27508,7 +27788,7 @@ var ts; // falls through case 243 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: if (node.parent.kind === 291 /* JSDocSignature */) { return bindParameter(node); } @@ -27516,13 +27796,13 @@ var ts; break; } // falls through - case 302 /* JSDocPropertyTag */: + case 303 /* JSDocPropertyTag */: var propTag = node; var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } @@ -27727,6 +28007,11 @@ var ts; } function bindSpecialPropertyAssignment(node) { var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } // Fix up parent pointers since we're going to use these nodes before we bind into them node.left.parent = node; node.right.parent = node; @@ -27910,7 +28195,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 296 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -28034,18 +28319,48 @@ var ts; // - node is not block scoped variable statement and at least one variable declaration has initializer // Rationale: we don't want to report errors on non-initialized var's since they are hoisted // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var isError = ts.unreachableCodeIsError(options) && + var isError_1 = ts.unreachableCodeIsError(options) && !(node.flags & 4194304 /* Ambient */) && (!ts.isVariableStatement(node) || !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || node.declarationList.declarations.some(function (d) { return !!d.initializer; })); - errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); } } } return true; } } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return true; + case 242 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 241 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || @@ -28619,7 +28934,7 @@ var ts; break; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; @@ -28896,7 +29211,7 @@ var ts; return 940049729 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: case 193 /* ParenthesizedExpression */: case 97 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; @@ -28920,7 +29235,7 @@ var ts; /** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -28996,7 +29311,7 @@ var ts; ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { - visitType(getConstraintFromTypeParameter(type)); + visitType(getConstraintOfTypeParameter(type)); } function visitUnionOrIntersectionType(type) { ts.forEach(type.types, visitType); @@ -29068,7 +29383,7 @@ var ts; } var t = getTypeOfSymbol(symbol); visitType(t); // Should handle members on classes and such - if (symbol.flags & 1955 /* HasExports */) { + if (symbol.exports) { symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { @@ -29158,7 +29473,6 @@ var ts; undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); - var moduleSymbol = createSymbol(4 /* Property */, "module"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; // for public members that accept a Node or one of its subtypes, we must guard against @@ -29202,6 +29516,7 @@ var ts; return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, getReturnTypeOfSignature: getReturnTypeOfSignature, getNullableType: getNullableType, getNonNullableType: getNonNullableType, @@ -29270,6 +29585,10 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); @@ -29280,12 +29599,11 @@ var ts; }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { - var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); - apparentArgumentCount = theArgumentCount; - var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; - apparentArgumentCount = undefined; - return res; + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); }, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); @@ -29322,7 +29640,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); @@ -29365,7 +29683,7 @@ var ts; getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentModule: function (node, target) { return getSuggestionForNonexistentModule(node, target); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -29384,6 +29702,9 @@ var ts; return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } var diagnostics; try { // Record the cancellation token so it can be checked later on during checkSourceElement. @@ -29403,8 +29724,8 @@ var ts; cancellationToken = undefined; } function addUnusedDiagnostics() { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { - if (!unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } }); @@ -29420,6 +29741,13 @@ var ts; } } }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } var tupleTypes = ts.createMap(); var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); @@ -29475,7 +29803,6 @@ var ts; var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); @@ -29647,7 +29974,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30089,6 +30416,7 @@ var ts; // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) // or if usage is in a type context: // 1. inside a type query (typeof in type position) + // 2. inside a jsdoc comment if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; @@ -30098,7 +30426,7 @@ var ts; return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { @@ -30381,7 +30709,7 @@ var ts; location = location.parent; } break; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); @@ -30415,10 +30743,6 @@ var ts; if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } - if (ts.isIdentifier(originalLocation) && ts.isPropertyAccessExpression(originalLocation.parent) && - originalLocation.escapedText === "module" && originalLocation.parent.name.escapedText === "exports") { - return moduleSymbol; - } } } if (!result) { @@ -30431,9 +30755,13 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { - suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } } if (!suggestion) { @@ -30642,7 +30970,7 @@ var ts; ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } } @@ -30786,7 +31114,7 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } } } @@ -30821,9 +31149,13 @@ var ts; if (!symbol) { var moduleName = getFullyQualifiedName(moduleSymbol); var declarationName = ts.declarationNameToString(name); - var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); @@ -31145,6 +31477,12 @@ var ts; var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -31157,8 +31495,8 @@ var ts; var errorInfo = packageId ? ts.chainDiagnosticMessages( /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0 - : ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)) + ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 + : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } @@ -31303,13 +31641,13 @@ var ts; } function getExportsOfModuleWorker(moduleSymbol) { var visitedSymbols = []; - // A module defined by an 'export=' consists on one export that needs to be resolved + // A module defined by an 'export=' consists of one export that needs to be resolved moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; // 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 & 1955 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { return; } var symbols = ts.cloneMap(symbol.exports); @@ -31354,17 +31692,25 @@ var ts; * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` */ - function getContainerOfSymbol(symbol) { + function getContainersOfSymbol(symbol, enclosingDeclaration) { var container = getParentOfSymbol(symbol); if (container) { - return container; + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + } + return ts.append(additionalContainers, container); } - var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); - if (!candidate) { + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { return undefined; } - var alias = getAliasForSymbolInContainer(candidate, symbol); - return alias ? candidate : undefined; + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { @@ -31388,9 +31734,7 @@ var ts; } } function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); @@ -31615,6 +31959,54 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -31625,55 +32017,20 @@ var ts; */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, - }; - } - return hasAccessibleDeclarations; - } - else { - if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { - // Any meaning of a module symbol is always accessible via an `import` type - return { - accessibility: 0 /* Accessible */ - }; - } - } - // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. - // It could be a qualified symbol and hence verify the path - // e.g.: - // module m { - // export class c { - // } - // } - // const x: typeof m.c - // In the above example when we start with checking if typeof m.c symbol is accessible, - // we are going to see if c can be accessed in scope directly. - // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible - // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getContainerOfSymbol(symbol); + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { accessibility: 2 /* CannotBeNamed */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), errorModuleName: symbolToString(symbolExternalModule) }; } @@ -31681,14 +32038,14 @@ var ts; // Just a local name that is not accessible return { accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 /* Accessible */ }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); @@ -31809,7 +32166,8 @@ var ts; function typeToString(type, enclosingDeclaration, flags, writer) { if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -31817,7 +32175,7 @@ var ts; var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } @@ -31862,11 +32220,17 @@ var ts; tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, - inferTypeParameters: undefined + inferTypeParameters: undefined, + approximateLength: 0 }; var resultingNode = cb(context); return context.encounteredError ? undefined : resultingNode; } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + } function typeToTypeNodeHelper(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); @@ -31878,66 +32242,83 @@ var ts; return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { return ts.createKeywordTypeNode(142 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(137 /* StringKeyword */); } if (type.flags & 8 /* Number */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(134 /* NumberKeyword */); } if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (type.flags & (64 /* StringLiteral */)) { + if (type.flags & 64 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & (128 /* NumberLiteral */)) { + if (type.flags & 128 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 256 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 2048 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } + context.approximateLength += 13; return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); } if (type.flags & 4096 /* Void */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(105 /* VoidKeyword */); } if (type.flags & 8192 /* Undefined */) { + context.approximateLength += 9; return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); } if (type.flags & 16384 /* Null */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(95 /* NullKeyword */); } if (type.flags & 32768 /* Never */) { + context.approximateLength += 5; return ts.createKeywordTypeNode(131 /* NeverKeyword */); } if (type.flags & 1024 /* ESSymbol */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(138 /* SymbolKeyword */); } if (type.flags & 16777216 /* NonPrimitive */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(135 /* ObjectKeyword */); } if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { @@ -31949,6 +32330,7 @@ var ts; context.tracker.reportInaccessibleThisError(); } } + context.approximateLength += 4; return ts.createThis(); } var objectFlags = ts.getObjectFlags(type); @@ -31958,6 +32340,7 @@ var ts; } if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && @@ -31966,7 +32349,9 @@ var ts; ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { - return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol @@ -31981,7 +32366,7 @@ var ts; } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; - var typeNodes = mapToTypeNodes(types, context); + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; @@ -32000,12 +32385,14 @@ var ts; } if (type.flags & 1048576 /* Index */) { var indexedType = type.type; + context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 2097152 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } if (type.flags & 4194304 /* Conditional */) { @@ -32016,6 +32403,7 @@ var ts; context.inferTypeParameters = saveInferTypeParameters; var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 8388608 /* Substitution */) { @@ -32038,6 +32426,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { @@ -32046,7 +32435,7 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); @@ -32065,6 +32454,7 @@ var ts; return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); } else { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } } @@ -32106,6 +32496,7 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { @@ -32124,6 +32515,7 @@ var ts; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function typeReferenceToTypeNode(type) { @@ -32240,6 +32632,9 @@ var ts; return ids; } function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; @@ -32262,8 +32657,10 @@ var ts; if (!properties) { return typeElements; } + var i = 0; for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + i++; if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { if (propertySymbol.flags & 4194304 /* Prototype */) { continue; @@ -32272,61 +32669,96 @@ var ts; context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); } } - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? - anyType : getTypeOfSymbol(propertySymbol); - var saveEnclosingDeclaration = context.enclosingDeclaration; - context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } - } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); - context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; - if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { - var signatures = getSignaturesOfType(propertyType, 0 /* Call */); - for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { - var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); - } - typeElements.push(methodDeclaration); - } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); } - else { - var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; - var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined); - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); - } - typeElements.push(propertySignature); + } + } + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); } + typeElements.push(methodDeclaration); } - return typeElements.length ? typeElements : undefined; + } + else { + var savedFlags = context.flags; + context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); } } - function mapToTypeNodes(types, context) { + function mapToTypeNodes(types, context, isBareList) { if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } var result = []; + var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -32348,6 +32780,7 @@ var ts; if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } + context.approximateLength += (name.length + 4); return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } @@ -32386,6 +32819,7 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { @@ -32407,14 +32841,14 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 296 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32436,6 +32870,7 @@ var ts; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); @@ -32465,16 +32900,18 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); - var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents)) { + for (var _i = 0, _a = parents; _i < _a.length; _i++) { + var parent = _a[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } } } } @@ -32484,10 +32921,12 @@ var ts; if ( // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } return [symbol]; } } @@ -32542,24 +32981,26 @@ var ts; } } } - return symbol.escapedName.substring(1, symbol.escapedName.length - 1); - } - else { - if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { - // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); - var links = getSymbolLinks(symbol); - var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); - if (!specifier) { - specifier = ts.flatten(ts.moduleSpecifiers.getModuleSpecifiers(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, context.tracker.moduleResolverHost.getSourceFiles(), // TODO: GH#18217 - { importModuleSpecifierPreference: "non-relative" }))[0]; - links.specifierCache = links.specifierCache || ts.createMap(); - links.specifierCache.set(contextFile.path, specifier); + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - return specifier; + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module @@ -32568,7 +33009,11 @@ var ts; // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); - var lit = ts.createLiteralTypeNode(ts.createLiteral(getSpecifierForModuleSymbol(chain[0], context))); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") if (!nonRootParts || ts.isEntityName(nonRootParts)) { if (nonRootParts) { var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; @@ -32602,6 +33047,7 @@ var ts; context.flags |= 16777216 /* InInitialEntityName */; } var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } @@ -32816,7 +33262,7 @@ var ts; function determineIfDeclarationIsVisible() { switch (node.kind) { case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); @@ -32969,23 +33415,19 @@ var ts; return -1; } function hasType(target, propertyName) { - if (propertyName === 0 /* Type */) { - return !!getSymbolLinks(target).type; - } - if (propertyName === 2 /* DeclaredType */) { - return !!getSymbolLinks(target).declaredType; - } - if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return !!target.resolvedBaseConstructorType; - } - if (propertyName === 3 /* ResolvedReturnType */) { - return !!target.resolvedReturnType; - } - if (propertyName === 4 /* ResolvedBaseConstraint */) { - var bc = target.resolvedBaseConstraint; - return !!bc && bc !== circularConstraintType; - } - return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + } + return ts.Debug.assertNever(propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -33032,7 +33474,7 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); @@ -33050,10 +33492,9 @@ var ts; } for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; - var inNamesToRemove = names.has(prop.escapedName); - var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); - var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); - if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { + if (!names.has(prop.escapedName) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { members.set(prop.escapedName, getNonReadonlySymbol(prop)); } } @@ -33261,17 +33702,17 @@ var ts; } } // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.escapedName === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } + else if (ts.isInJavaScriptFile(declaration)) { + var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); + if (expandoType) { + return expandoType; + } + } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); @@ -33289,96 +33730,46 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); if (specialDeclaration) { - return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var tag = ts.getJSDocTypeTag(specialDeclaration); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); + return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); } - var types = []; - var constructorTypes; var definedInConstructor = false; var definedInMethod = false; - var jsDocType; - var _loop_4 = function (declaration) { - var declarationInConstructor = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; var expression = ts.isBinaryExpression(declaration) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { - return { value: errorType }; + return errorType; } var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); if (special === 4 /* ThisProperty */) { - var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); - // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. - // Function expressions that are assigned to the prototype count as methods. - declarationInConstructor = thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 237 /* FunctionDeclaration */ || - (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); - if (declarationInConstructor) { + if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } else { definedInMethod = true; } } - // If there is a JSDoc type, use it - var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type_1) { - var declarationType = getWidenedType(type_1); - if (!jsDocType) { - jsDocType = declarationType; - } - else if (jsDocType !== errorType && declarationType !== errorType && - !isTypeIdenticalTo(jsDocType, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { - errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); - } - } - else if (!jsDocType && ts.isBinaryExpression(expression)) { - // If we don't have an explicit JSDoc type, get the type from the expression. - var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); - if (ts.getObjectFlags(type_2) & 16 /* Anonymous */ && - special === 2 /* ModuleExports */ && - symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type_2); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); - symbol.exports.forEach(function (s, name) { - if (members_3.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); - } - else { - members_3.set(name, s); - } - }); - type_2 = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); - } - var anyedType = type_2; - if (isEmptyArrayLiteralType(type_2)) { - anyedType = anyArrayType; - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } - } - types.push(anyedType); - if (declarationInConstructor) { - (constructorTypes || (constructorTypes = [])).push(anyedType); - } + jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!jsdocType) { + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); } - }; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var state_2 = _loop_4(declaration); - if (typeof state_2 === "object") - return state_2.value; } - var type = jsDocType; + var type = jsdocType; if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfSpecialPropertyOfBaseType(symbol); @@ -33399,6 +33790,91 @@ var ts; } return widened; } + function getJSExpandoObjectType(decl, symbol, init) { + if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 131072 /* Object */ && + special === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 155 /* Constructor */ || + thisContainer.kind === 237 /* FunctionDeclaration */ || + (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } /** check for definition in base class if any declaration is in a class */ function getTypeOfSpecialPropertyOfBaseType(specialProperty) { var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { @@ -33536,138 +34012,104 @@ var ts; } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - // Handle prototype property - if (symbol.flags & 4194304 /* Prototype */) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - // CommonsJS require and module both have type any. - if (symbol === requireSymbol || symbol === moduleSymbol) { - return links.type = anyType; - } - // Handle catch clause variables - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; - } - if (declaration.kind === 252 /* ExportAssignment */) { - return links.type = checkExpression(declaration.expression); - } - // Handle variable, parameter or property - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; - } - var type = getJSSpecialType(symbol, declaration); - if (!type) { - if (ts.isJSDocPropertyLikeTag(declaration) - || ts.isPropertyAccessExpression(declaration) - || ts.isIdentifier(declaration) - || ts.isClassDeclaration(declaration) - || ts.isFunctionDeclaration(declaration) - || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { - // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - return getTypeOfFuncClassEnumModule(symbol); - } - type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; - } - else if (ts.isPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); - } - else if (ts.isJsxAttribute(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); - } - else if (ts.isShorthandPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); - } - else if (ts.isObjectLiteralMethod(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); - } - else if (ts.isParameter(declaration) - || ts.isPropertyDeclaration(declaration) - || ts.isPropertySignature(declaration) - || ts.isVariableDeclaration(declaration) - || ts.isBindingElement(declaration)) { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); - } - else { - return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); - } - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); } - function getJSSpecialType(symbol, decl) { - if (!ts.isInJavaScriptFile(decl)) { - return undefined; + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + } + if (declaration.kind === 252 /* ExportAssignment */) { + return checkExpression(declaration.expression); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJavaScriptFile(declaration) && + (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromJSPropertyAssignments(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } - else if (ts.isJSDocPropertyLikeTag(decl) && decl.typeExpression) { - return getTypeFromTypeNode(decl.typeExpression.type); - } - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - else if (ts.isBinaryExpression(decl) || - ts.isPropertyAccessExpression(decl) && ts.isBinaryExpression(decl.parent)) { - return getJSInitializerType(decl, symbol, ts.getAssignedJavascriptInitializer(ts.isBinaryExpression(decl) ? decl.left : decl)) || - getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else if (ts.isParameter(decl) - || ts.isPropertyDeclaration(decl) - || ts.isPropertySignature(decl) - || ts.isVariableDeclaration(decl) - || ts.isBindingElement(decl)) { - // Use type from type annotation if one is present - var isOptional = ts.isParameter(decl) && isJSDocOptionalParameter(decl) || - !ts.isBindingElement(decl) && !ts.isVariableDeclaration(decl) && !!decl.questionToken; - var declaredType = tryGetTypeFromEffectiveTypeNode(decl); - return declaredType && addOptionality(declaredType, isOptional) || - getJSInitializerType(decl, symbol, ts.getDeclaredJavascriptInitializer(decl)) || - getWidenedTypeForVariableLikeDeclaration(decl, /*includeOptionality*/ true); - } - } - function getJSInitializerType(decl, symbol, init) { - if (init && ts.isInJavaScriptFile(init) && ts.isObjectLiteralExpression(init)) { - var exports_1 = ts.createSymbolTable(); - while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { - var s_1 = getSymbolOfNode(decl); - if (s_1 && ts.hasEntries(s_1.exports)) { - mergeSymbolTable(exports_1, s_1.exports); - } - decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; - } - var s = getSymbolOfNode(decl); - if (s && ts.hasEntries(s.exports)) { - mergeSymbolTable(exports_1, s.exports); - } - return createAnonymousType(symbol, exports_1, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + return type; } - function getAnnotatedAccessorType(accessor) { + function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { if (accessor.kind === 156 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); - return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + return getterTypeAnnotation; } else { var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + return setterTypeAnnotation; } } return undefined; } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } function getAnnotatedAccessorThisParameter(accessor) { var parameter = getAccessorThisParameter(accessor); return parameter && parameter.symbol; @@ -33677,60 +34119,60 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; } - var type = void 0; - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; } else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); } + // Otherwise, fall back to 'any'. else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } - type = anyType; } + type = anyType; } } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); - } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } - links.type = type; } - return links.type; + return type; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -33738,6 +34180,7 @@ var ts; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); + var originalLinks = links; if (!links.type) { var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); if (jsDeclaration) { @@ -33756,32 +34199,45 @@ var ts; } } } - if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else if (symbol.valueDeclaration.kind === 202 /* BinaryExpression */ || - symbol.valueDeclaration.kind === 187 /* PropertyAccessExpression */ && symbol.valueDeclaration.parent.kind === 202 /* BinaryExpression */) { - links.type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - var type = createObjectType(16 /* Anonymous */, symbol); - if (symbol.flags & 32 /* Class */) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 202 /* BinaryExpression */ || + declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { + return getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; } - else { - links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); } + return type_1; } } - return links.type; + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } } function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); } function getTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); @@ -33807,7 +34263,7 @@ var ts; } else { if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type = errorType; } symbolInstantiationDepth++; var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); @@ -33911,8 +34367,8 @@ var ts; case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: case 240 /* TypeAliasDeclaration */: - case 300 /* JSDocTemplateTag */: - case 301 /* JSDocTypedefTag */: + case 301 /* JSDocTemplateTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: case 179 /* MappedType */: case 173 /* ConditionalType */: @@ -33975,15 +34431,18 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return false; + return isJavascriptConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + var isJavascript = ts.isInJavaScriptFile(location); + if (isJavascriptConstructorType(type) && !typeArgCount) { + return getSignaturesOfType(type, 0 /* Call */); + } + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); @@ -34070,6 +34529,9 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } + else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere @@ -34404,7 +34866,8 @@ var ts; } /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ function isThislessTypeParameter(node) { - return !node.constraint || isThislessType(node.constraint); + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); } /** * A variable-like declaration is free of this references if it has a type annotation @@ -34502,6 +34965,11 @@ var ts; && ts.isEntityNameExpression(node.expression) && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } /** * Indicates whether a declaration has a late-bindable dynamic name. */ @@ -34939,7 +35407,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_4 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -34962,7 +35430,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_4(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35066,7 +35534,7 @@ var ts; // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), /*_index*/ undefined, prop); + addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -35084,7 +35552,7 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - function addMemberForKeyType(t, _index, origin) { + function addMemberForKeyType(t) { // 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. @@ -35106,9 +35574,9 @@ var ts; prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : propType; - if (origin) { - prop.syntheticOrigin = origin; - prop.declarations = origin.declarations; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; } prop.nameType = t; members.set(propName, prop); @@ -35136,7 +35604,7 @@ var ts; errorType); } function getConstraintDeclarationForMappedType(type) { - return type.declaration.typeParameter.constraint; + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 @@ -35264,11 +35732,7 @@ var ts; return obj.properties.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - if (expected && typeIsLiteralType(expected)) { - var actual = getTypeOfNode(property); - return !!actual && !isTypeIdenticalTo(actual, expected); - } - return false; + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -35377,20 +35841,12 @@ var ts; } return undefined; } - function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { + function getBaseConstraintOfType(type) { if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - } - function getBaseConstraintOfType(type) { - var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); - if (!constraint && type.flags & 1048576 /* Index */) { - return keyofConstraintType; - } - return constraint; + return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35408,23 +35864,24 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var circular; - if (!type.resolvedBaseConstraint) { - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + var result = computeBaseConstraint(getSimplifiedType(t)); + if (!popTypeResolution()) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; } - return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { - circular = true; - return undefined; - } - var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { - circular = true; - return undefined; - } - return result; + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { if (t.flags & 65536 /* TypeParameter */) { @@ -35437,8 +35894,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_3 = types_4[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_4[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -35533,6 +35990,7 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; + var indexTypes; var isUnion = containingType.flags & 262144 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols @@ -35558,14 +36016,21 @@ var ts; } } else if (isUnion) { - checkFlags |= 16 /* Partial */; + var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); + if (index) { + checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, index.type); + } + else { + checkFlags |= 16 /* Partial */; + } } } } if (!props) { return undefined; } - if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } var declarations; @@ -35597,6 +36062,7 @@ var ts; } propTypes.push(type); } + ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && commonValueDeclaration) { @@ -35767,17 +36233,6 @@ var ts; var isBracketed = node.isBracketed, typeExpression = node.typeExpression; return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; } - function createTypePredicateFromTypePredicateNode(node) { - var parameterName = node.parameterName; - var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { - return createIdentifierTypePredicate(parameterName && parameterName.escapedText, // TODO: GH#18217 - parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); - } - else { - return createThisTypePredicate(type); - } - } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; } @@ -35853,7 +36308,7 @@ var ts; var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } - if (i === 0 && paramSymbol.escapedName === "this") { + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { hasThisParameter = true; thisParameter = param.symbol; } @@ -35887,9 +36342,9 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -35917,26 +36372,14 @@ var ts; parameters.push(syntheticArgsSymbol); return true; } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 - } - else if (classType) { - return classType; - } - var typeNode = ts.getEffectiveReturnTypeNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); - } - // TypeScript 1.0 spec (April 2014): - // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); } function containsArgumentsReference(declaration) { var links = getNodeLinks(declaration); @@ -36016,52 +36459,105 @@ var ts; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJavaScriptFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type) : - noTypePredicate; + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 71 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + type = anyType; } signature.resolvedReturnType = type; } return signature.resolvedReturnType; } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 155 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } function isResolvingReturnTypeOfSignature(signature) { return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */) || anyType; + return type && getIndexTypeOfType(type, 1 /* Number */); } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36161,7 +36657,7 @@ var ts; } function getConstraintDeclaration(type) { var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); - return decl && decl.constraint; + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { var inferences; @@ -36207,6 +36703,7 @@ var ts; } return inferences && getIntersectionType(inferences); } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { if (typeParameter.target) { @@ -36222,7 +36719,9 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */).parent); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); } function getTypeListId(types) { var result = ""; @@ -36412,6 +36911,10 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } + var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag && enumTag.typeExpression) { + return getTypeFromTypeNode(enumTag.typeExpression); + } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -36461,7 +36964,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 162 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -36552,7 +37055,7 @@ var ts; // The expression is processed as an identifier expression (section 4.3) // or property access expression(section 4.10), // the widened type(section 3.9) of which becomes the result. - links.resolvedType = getWidenedType(checkExpression(node.exprName)); + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); } return links.resolvedType; } @@ -36671,6 +37174,9 @@ var ts; function createArrayType(elementType) { return createTypeFromGenericGlobalType(globalArrayType, [elementType]); } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -36769,6 +37275,14 @@ var ts; function containsType(types, type) { return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } // Return true if the given intersection type contains // more than one unit type or, // an object type and a nullable type (null or undefined), or @@ -36932,7 +37446,7 @@ var ts; includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, includes & 16749629 /* NotUnit */ ? 0 : 67108864 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37047,29 +37561,65 @@ var ts; } } } - // When intersecting unions of unit types we can simply intersect based on type identity. - // Here we remove all unions of unit types from the given list and replace them with a - // a single union containing an intersection of the unit types. - function intersectUnionsOfUnitTypes(types) { - var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfUnitTypes */) !== 0; }); - var unionType = types[unionIndex]; - var intersection = unionType.types; - var i = types.length - 1; - var _loop_6 = function () { + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 64 /* StringLiteral */ ? stringType : + type.flags & 128 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfUnitTypes */) { - intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } - i--; - }; - while (i > unionIndex) { - _loop_6(); + else { + i++; + } } - if (intersection === unionType.types) { + // Return false if there was only one union of primitive types + if (!unionTypes) { return false; } - types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 67108864 /* UnionOfUnitTypes */); + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -37109,7 +37659,7 @@ var ts; return typeSet[0]; } if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -37220,6 +37770,33 @@ var ts; type.indexType = indexType; return type; } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 262144 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 524288 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 15794176 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : @@ -37239,7 +37816,8 @@ var ts; getNodeLinks(accessNode).resolvedSymbol = prop; } } - return getTypeOfSymbol(prop); + var propType = getTypeOfSymbol(prop); + return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; } if (isTupleType(objectType)) { var restType = getRestTypeOfTupleType(objectType); @@ -37249,7 +37827,7 @@ var ts; } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (isTypeAny(objectType)) { + if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { return objectType; } var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || @@ -37268,9 +37846,15 @@ var ts; if (indexType.flags & 32768 /* Never */) { return neverType; } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1 /* Number */)) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); } else { @@ -37288,6 +37872,9 @@ var ts; return anyType; } } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessNode) { var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { @@ -37374,7 +37961,7 @@ var ts; return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 65536 /* TypeParameter */) { - var constraint = getConstraintFromTypeParameter(objectType); + var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); } @@ -37601,19 +38188,17 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var argumentType = getTypeFromTypeNode(node.argument); - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type - var moduleName = argumentType.value; - var innerModuleSymbol = resolveExternalModule(node, moduleName, ts.Diagnostics.Cannot_find_module_0, node, /*isForAugmentation*/ false); + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var moduleSymbol_1 = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); - var currentNamespace = moduleSymbol_1; + var currentNamespace = moduleSymbol; var current = void 0; while (current = nameStack.shift()) { var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; @@ -37629,14 +38214,14 @@ var ts; resolveImportSymbolType(node, links, currentNamespace, targetMeaning); } else { - if (moduleSymbol_1.flags & targetMeaning) { - resolveImportSymbolType(node, links, moduleSymbol_1, targetMeaning); + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { var errorMessage = targetMeaning === 67216319 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; - error(node, errorMessage, moduleName); + error(node, errorMessage, node.argument.literal.text); links.resolvedSymbol = unknownSymbol; links.resolvedType = errorType; } @@ -37722,20 +38307,16 @@ var ts; } for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; - // we approximate own properties as non-methods plus methods that are inside the object literal - var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.escapedName, true); } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + else if (isSpreadableProperty(rightProp)) { members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { var leftProp = _c[_b]; - if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) - || skippedPrivateMembers.has(leftProp.escapedName) - || isClassMethod(leftProp)) { + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { continue; } if (members.has(leftProp.escapedName)) { @@ -37762,6 +38343,12 @@ var ts; spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) + ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) + : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { return prop; @@ -37780,9 +38367,6 @@ var ts; } return index; } - function isClassMethod(prop) { - return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } function createLiteralType(flags, value, symbol) { var type = createType(flags); type.symbol = symbol; @@ -37942,7 +38526,7 @@ var ts; case 71 /* Identifier */: case 146 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: return errorType; } @@ -38118,7 +38702,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavaScriptConstructor(declaration_1)) { + if (isJavascriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38178,11 +38762,16 @@ var ts; } } 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 - // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated - // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for - // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a - // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & 1048576 /* Index */) { var typeVariable_1 = constraintType.type; @@ -38191,7 +38780,11 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); + var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); } return t; }); @@ -38203,6 +38796,25 @@ var ts; function isMappableType(type) { return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + propType; + } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { @@ -38354,6 +38966,9 @@ var ts; return true; } } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); @@ -38365,7 +38980,7 @@ var ts; function getTypeWithoutSignatures(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { + if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; @@ -38505,8 +39120,8 @@ var ts; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } - if (!issuedElaboration && (ts.length(targetProp && targetProp.declarations) || ts.length(target.symbol && target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); } } reportedError = true; @@ -38655,9 +39270,9 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceRestTypeParameter = getRestTypeParameter(source); - var targetRestTypeParameter = sourceRestTypeParameter ? getRestTypeParameter(target) : undefined; - if (sourceRestTypeParameter && !(targetRestTypeParameter && sourceCount === targetCount)) { + var sourceGenericRestType = getGenericRestType(source); + var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; + if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -38683,8 +39298,8 @@ var ts; var paramCount = Math.max(sourceCount, targetCount); var lastIndex = paramCount - 1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceRestTypeParameter || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetRestTypeParameter || getTypeAtPosition(target, i); + var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); + var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -38710,11 +39325,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? + getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? + getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39219,6 +39836,9 @@ var ts; return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && @@ -39229,7 +39849,7 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_7 = function (prop) { + var _loop_5 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -39268,9 +39888,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_7(prop); - if (typeof state_3 === "object") - return state_3.value; + var state_2 = _loop_5(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -39302,7 +39922,8 @@ var ts; } if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || - findMatchingTypeReferenceOrTypeAliasReference(source, target); + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39324,6 +39945,11 @@ var ts; }); } } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -39923,8 +40549,12 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); + var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { // An abstract constructor type is not assignable to a non-abstract constructor type @@ -40174,7 +40804,7 @@ var ts; return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -40436,6 +41066,9 @@ var ts; function isArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray @@ -40618,7 +41251,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; - regularNew.objectFlags |= 128 /* ObjectLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; } @@ -40696,7 +41329,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); - return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); @@ -40828,13 +41463,13 @@ var ts; sourceHasRest ? targetCount : targetHasRest ? sourceCount : Math.min(sourceCount, targetCount); - var targetRestTypeVariable = getRestTypeParameter(target); - var paramCount = targetRestTypeVariable ? Math.min(targetCount - 1, maxCount) : maxCount; + var targetGenericRestType = getGenericRestType(target); + var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetRestTypeVariable) { - callback(getRestTypeAtPosition(source, paramCount), targetRestTypeVariable); + if (targetGenericRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -40946,6 +41581,22 @@ var ts; return undefined; } } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; @@ -41510,7 +42161,7 @@ var ts; case 71 /* Identifier */: return ts.idText(name); case 147 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; @@ -41534,8 +42185,9 @@ var ts; case 97 /* SuperKeyword */: return target.kind === 97 /* SuperKeyword */; case 187 /* PropertyAccessExpression */: - return target.kind === 187 /* PropertyAccessExpression */ && - source.name.escapedText === target.name.escapedText && + case 188 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); case 184 /* BindingElement */: if (target.kind !== 187 /* PropertyAccessExpression */) @@ -41553,6 +42205,11 @@ var ts; } return false; } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } function containsMatchingReference(source, target) { while (source.kind === 187 /* PropertyAccessExpression */) { source = source.expression; @@ -41632,18 +42289,6 @@ var ts; } return flow.id; } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 262144 /* Union */)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -41652,7 +42297,7 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); if (!(reducedType.flags & 32768 /* Never */)) { return reducedType; } @@ -41908,7 +42553,7 @@ var ts; if (type.flags & 262144 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfUnitTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); } return f(type) ? type : neverType; } @@ -42150,7 +42795,10 @@ var ts; 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 !== 187 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + if (container && container !== flowContainer && + reference.kind !== 187 /* PropertyAccessExpression */ && + reference.kind !== 188 /* ElementAccessExpression */ && + reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -42379,13 +43027,22 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 187 /* PropertyAccessExpression */ && - computedType.flags & 262144 /* Union */ && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(computedType, expr.name.escapedText); + if (!(computedType.flags & 262144 /* Union */) || + expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.escapedText; + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); @@ -42669,6 +43326,7 @@ var ts; case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); case 189 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); @@ -42885,6 +43543,7 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -42896,7 +43555,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || node.parent.kind === 211 /* NonNullExpression */ || @@ -43059,15 +43718,14 @@ var ts; // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); - var needToCaptureLexicalThis = false; + var capturedByArrowFunction = false; if (container.kind === 155 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. if (container.kind === 195 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); - // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); + capturedByArrowFunction = true; } switch (container.kind) { case 242 /* ModuleDeclaration */: @@ -43095,13 +43753,16 @@ var ts; error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } - if (needToCaptureLexicalThis) { + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { captureLexicalThis(node, container); } var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); } return type || anyType; } @@ -43110,8 +43771,8 @@ var ts; if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. Check if it's the RHS - // of a x.prototype.y = function [name]() { .... } + // If this is a function in a JS file, it might be a class method. + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } if (container.kind === 194 /* FunctionExpression */ && container.parent.kind === 202 /* BinaryExpression */ && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { @@ -43125,6 +43786,17 @@ var ts; return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); } } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJavascriptClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return getFlowTypeOfReference(node, thisType); @@ -43148,7 +43820,7 @@ var ts; var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && - jsDocFunctionType.parameters[0].name.escapedText === "this") { + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } @@ -43437,20 +44109,10 @@ var ts; } var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameter = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameter ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - // If last parameter is contextually rest parameter get its type - if (funcHasRestParameter && indexOfParameter === len) { - return getRestTypeAtPosition(contextualSignature, indexOfParameter); - } + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); } } // In a variable, parameter or property declaration with a type annotation, @@ -43536,10 +44198,9 @@ var ts; function getContextualReturnType(functionDecl) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.kind === 155 /* Constructor */ || - ts.getEffectiveReturnTypeNode(functionDecl) || - isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature @@ -43588,22 +44249,39 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments to avoid circularity. + // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function isContextSensitiveAssignment(binaryExpression) { var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); switch (kind) { case 0 /* None */: return true; case 5 /* Property */: - // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. - // See `bindStaticPropertyAssignment` in `binder.ts`. - return !binaryExpression.left.symbol; case 1 /* ExportsProperty */: - case 2 /* ModuleExports */: + case 6 /* Prototype */: case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + if (ts.isInJavaScriptFile(decl)) { + return !!ts.getJSDocTypeTag(decl); + } + else if (ts.isIdentifier(binaryExpression.left.expression)) { + var id = binaryExpression.left.expression; + var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); + return !ts.isFunctionSymbol(parentSymbol); + } + return true; + } case 4 /* ThisProperty */: - case 6 /* Prototype */: - return false; + case 2 /* ModuleExports */: + return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); default: return ts.Debug.assertNever(kind); } @@ -44018,16 +44696,11 @@ var ts; // union type of return types from these signatures function getContextualSignature(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type; - if (ts.isInJavaScriptFile(node)) { - var jsdoc = ts.getJSDocType(node); - if (jsdoc) { - type = getTypeFromTypeNode(jsdoc); - } - } - if (!type) { - type = getContextualTypeForFunctionLikeDeclaration(node); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; } + var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } @@ -44235,7 +44908,8 @@ var ts; var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); - var isJSObjectLiteral = !contextualType && isInJSFile; + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44259,6 +44933,9 @@ var ts; checkTypeAssignableTo(type, jsDocType, memberDecl); type = jsDocType; } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } } typeFlags |= type.flags; var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? @@ -44368,12 +45045,15 @@ var ts; } return createObjectLiteralType(); function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); result.objectFlags |= 128 /* ObjectLiteral */; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } @@ -44760,7 +45440,7 @@ var ts; var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); @@ -44796,7 +45476,7 @@ var ts; if (jsxStatelessElementType) { // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); var result = void 0; var allMatchingAttributesType = void 0; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { @@ -45104,6 +45784,10 @@ var ts; } } } + else if (targetType.flags & 4194304 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } return false; } /** @@ -45161,11 +45845,6 @@ var ts; return errorType; } } - // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized - // '.prototype' property as well as synthesized tuple index properties. - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 152 /* PropertyDeclaration */; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } @@ -45187,23 +45866,19 @@ var ts; * Check whether the requested property access is valid. * Returns true if node is a valid property access, and false otherwise. * @param node The node to be checked. - * @param left The left hand side of the property access (e.g.: the super in `super.foo`). - * @param type The type of left. - * @param prop The symbol for the right hand side of the property access. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, left, type, prop) { + function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 187 /* PropertyAccessExpression */ || node.kind === 235 /* VariableDeclaration */ ? - node.name : - node.kind === 181 /* ImportType */ ? - node : - node.right; + var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or // instance member variable initializer where this references a derived class instance, @@ -45250,7 +45925,7 @@ var ts; } // Property is known to be protected at this point // All protected properties of a supertype are accessible in a super access - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { return true; } // Find the first enclosing class that has the declaring classes of the protected constituents @@ -45269,7 +45944,7 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintFromTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { @@ -45290,10 +45965,7 @@ var ts; return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; } function symbolHasNonMethodDeclaration(symbol) { - return forEachProperty(symbol, function (prop) { - var propKind = getDeclarationKindFromSymbol(prop); - return propKind !== 154 /* MethodDeclaration */ && propKind !== 153 /* MethodSignature */; - }); + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); @@ -45339,6 +46011,9 @@ var ts; if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } @@ -45353,7 +46028,7 @@ var ts; checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); @@ -45411,7 +46086,7 @@ var ts; diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializer(node) { @@ -45456,6 +46131,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; + var relatedInfo; if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; @@ -45465,32 +46141,44 @@ var ts; } } } - var promisedType = getPromisedTypeOfPromise(containingType); - if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - 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), suggestion); + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion_1 = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion_1 !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion_1); + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { - var suggestion = getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); @@ -45500,10 +46188,17 @@ var ts; // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - return result && ts.symbolName(result); + return result; + } + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); } - function getSuggestionForNonexistentModule(name, targetModule) { - var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); return suggestion && ts.symbolName(suggestion); } /** @@ -45547,15 +46242,15 @@ var ts; function isValidPropertyAccess(node, propertyName) { switch (node.kind) { case 187 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression, propertyName, getWidenedType(checkExpression(node.expression))); + return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); case 146 /* QualifiedName */: - return isValidPropertyAccessWithType(node, node.left, propertyName, getWidenedType(checkExpression(node.left))); + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); case 181 /* ImportType */: - return isValidPropertyAccessWithType(node, node, propertyName, getTypeFromTypeNode(node)); + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 181 /* ImportType */ ? node : node.expression, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -45575,14 +46270,14 @@ var ts; inferTypes(context.inferences, actualThisType, signatureThisType); return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); } - function isValidPropertyAccessWithType(node, left, propertyName, type) { + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { if (type === errorType || isTypeAny(type)) { return true; } var prop = getPropertyOfType(type, propertyName); - return prop ? checkPropertyAccessibility(node, left, type, prop) + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -45778,7 +46473,6 @@ var ts; function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call - var typeArguments; // Type arguments (undefined if none) var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { @@ -45789,7 +46483,6 @@ var ts; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = node.typeArguments; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. @@ -45806,7 +46499,6 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { @@ -45818,12 +46510,8 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } - if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { - return false; - } // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. if (spreadArgIndex >= 0) { return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); @@ -45927,8 +46615,8 @@ var ts; // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var restTypeParameter = getRestTypeParameter(signature); - var argCount = restTypeParameter ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var genericRestType = getGenericRestType(signature); + var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. @@ -45946,9 +46634,9 @@ var ts; inferTypes(context.inferences, argType, paramType); } } - if (restTypeParameter) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, restTypeParameter, context); - inferTypes(context.inferences, spreadType, restTypeParameter); + if (genericRestType) { + var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); + inferTypes(context.inferences, spreadType, genericRestType); } // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed @@ -46344,7 +47032,7 @@ var ts; node.kind === 157 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - var propertyType = getTypeOfNode(node); // TODO: GH#18217 + var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); @@ -46410,18 +47098,54 @@ var ts; return arg; } } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + min = Math.min(min, minCount); + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } var paramCount = min === max ? min : min + "-" + max; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; var isDecorator = node.kind === 150 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -46493,11 +47217,12 @@ var ts; // foo(0); // var candidateForArgumentError; + var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -46533,73 +47258,30 @@ var ts; // an error, we don't need to exclude any arguments, although it would cause no harm to do so. checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { - var min_1 = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; - min_1 = Math.min(min_1, getMinArgumentCount(sig)); - max = Math.max(max, getParameterCount(sig)); - } - var hasRestParameter_1 = ts.some(signatures, hasEffectiveRestParameter); - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - var paramCount = hasRestParameter_1 ? min_1 : - min_1 < max ? min_1 + "-" + max : - min_1; - var argCount = args.length; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - ts.Diagnostics.Expected_0_arguments_but_got_1; - diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + diagnostics.add(getArgumentArityError(node, signatures, args)); } else if (fallbackError) { diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } - // No signature was applicable. We have already reported the errors for the invalid signature. - // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. - // Pick the longest signature. This way we can get a contextual type for cases like: - // declare function f(a: { xa: number; xb: number; }, b: number); - // f({ | - // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: - // declare function f(k: keyof T); - // f(" - if (!produceDiagnostics) { - ts.Debug.assert(candidates.length > 0); // Else would have exited above. - var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); - var candidate = candidates[bestIndex]; - var typeParameters = candidate.typeParameters; - if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); // TODO: GH#18217 - while (typeArguments_1.length > typeParameters.length) { - typeArguments_1.pop(); - } - while (typeArguments_1.length < typeParameters.length) { - typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); - } - var instantiated = createSignatureInstantiation(candidate, typeArguments_1); - candidates[bestIndex] = instantiated; - return instantiated; - } - return candidate; - } - return resolveErrorCall(node); + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -46610,7 +47292,7 @@ var ts; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; @@ -46636,6 +47318,12 @@ var ts; } var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = candidate; + break; + } } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; @@ -46657,6 +47345,87 @@ var ts; return undefined; } } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_6 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_6(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments); + candidates[bestIndex] = instantiated; + return instantiated; + } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; var maxParams = -1; @@ -46673,11 +47442,14 @@ var ts; } return maxParamsIndex; } - function resolveCallExpression(node, candidatesOutArray) { + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { - ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } return anySignature; } if (superType !== errorType) { @@ -46686,7 +47458,7 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); } } return resolveUntypedCall(node); @@ -46729,7 +47501,12 @@ var ts; } return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * TS 1.0 spec: 4.12 @@ -46741,7 +47518,7 @@ var ts; return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } - function resolveNewExpression(node, candidatesOutArray) { + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { @@ -46789,7 +47566,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray); + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -46797,8 +47574,8 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } if (getThisTypeOfSignature(signature) === voidType) { @@ -46809,6 +47586,38 @@ var ts; invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 524288 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } function isConstructorAccessible(node, signature) { if (!signature || !signature.declaration) { return true; @@ -46824,16 +47633,10 @@ var ts; // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); - if (containingClass) { + if (containingClass && modifiers & 16 /* Protected */) { var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; } } if (modifiers & 8 /* Private */) { @@ -46865,7 +47668,7 @@ var ts; addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); if (apparentType === errorType) { @@ -46881,7 +47684,7 @@ var ts; invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -46906,7 +47709,7 @@ var ts; /** * Resolves a decorator as if it were a call expression. */ - function resolveDecorator(node, candidatesOutArray) { + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); if (apparentType === errorType) { @@ -46931,7 +47734,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -46955,30 +47758,30 @@ var ts; * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; * the function will fill it up with appropriate candidate signatures */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); } return undefined; } - function resolveSignature(node, candidatesOutArray) { + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { case 189 /* CallExpression */: - return resolveCallExpression(node, candidatesOutArray); + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); case 190 /* NewExpression */: - return resolveNewExpression(node, candidatesOutArray); + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); case 191 /* TaggedTemplateExpression */: - return resolveTaggedTemplateExpression(node, candidatesOutArray); + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); case 150 /* Decorator */: - return resolveDecorator(node, candidatesOutArray); + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); case 260 /* JsxOpeningElement */: case 259 /* JsxSelfClosingElement */: // This code-path is called by language service var exprTypes = checkExpression(node.tagName); return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); if (sfcResult && sfcResult !== unknownSignature) { return sfcResult; } @@ -46998,7 +47801,8 @@ var ts; * the function will fill it up with appropriate candidate signatures * @return a signature of the call-like expression or undefined if one can't be found */ - function getResolvedSignature(node, candidatesOutArray) { + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } var links = getNodeLinks(node); // If getResolvedSignature has already been called, we will have cached the resolvedSignature. // However, it is possible that either candidatesOutArray was not passed in the first time, @@ -47009,7 +47813,7 @@ var ts; return cached; } links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); // If signature resolution originated in control flow type analysis (for example to compute the // assigned type in a flow assignment) we don't cache the result as it may be based on temporary // types from the control flow analysis. @@ -47020,7 +47824,7 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavaScriptConstructor(node) { + function isJavascriptConstructor(node) { if (node && ts.isInJavaScriptFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) @@ -47033,14 +47837,21 @@ var ts; } return false; } - function getJavaScriptClassType(symbol) { + function isJavascriptConstructorType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJavascriptClassType(symbol) { var inferred; - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47113,7 +47924,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavaScriptClassType(funcSymbol); + var type = funcSymbol && getJavascriptClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47139,7 +47950,8 @@ var ts; if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { - jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; } } } @@ -47256,7 +48068,7 @@ var ts; if (produceDiagnostics && targetType !== errorType) { var widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); } } return targetType; @@ -47323,6 +48135,9 @@ var ts; return restParameter.escapedName; } function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); @@ -47333,22 +48148,19 @@ var ts; if (pos - paramCount < getLengthOfTupleType(restType)) { return restType.typeArguments[pos - paramCount]; } - var tupleRestType = getRestTypeOfTupleType(restType); - if (tupleRestType) { - return tupleRestType; - } + return getRestTypeOfTupleType(restType); } - return getIndexTypeOfType(restType, 1 /* Number */) || anyType; + return getIndexTypeOfType(restType, 1 /* Number */); } - return anyType; + return undefined; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); var hasRest = hasEffectiveRestParameter(source); if (hasRest && pos === paramCount - 1) { - var restTypeVariable = getRestTypeParameter(source); - if (restTypeVariable) { - return restTypeVariable; + var genericRestType = getGenericRestType(source); + if (genericRestType) { + return genericRestType; } } var start = hasRest ? Math.min(pos, paramCount - 1) : pos; @@ -47394,10 +48206,10 @@ var ts; } return signature.minArgumentCount; } - function getRestTypeParameter(signature) { + function getGenericRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 65536 /* TypeParameter */) { + if (restType.flags & 15794176 /* Instantiable */) { return restType; } } @@ -47665,7 +48477,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -47696,7 +48508,7 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 3 /* AnyOrUnknown */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. @@ -47737,6 +48549,16 @@ var ts; ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + } return anyFunctionType; } // Grammar checking @@ -47768,7 +48590,7 @@ var ts; contextualSignature : instantiateSignature(contextualSignature, contextualMapper); assignContextualParameterTypes(signature, instantiatedContextualSignature); } - if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, checkMode); if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; @@ -47781,20 +48603,21 @@ var ts; } return type; } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - var returnOrPromisedType = returnTypeNode && - ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : // Async function - getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { - if (!returnTypeNode) { + if (!ts.getEffectiveReturnTypeNode(node)) { // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors // we need. An example is the noImplicitAny errors resulting from widening the return expression // of a function. Because checking of function expression bodies is deferred, there was never an @@ -47858,7 +48681,7 @@ var ts; // If func.parent is a class and symbol is a (readonly) property of that class, or // if func is a constructor and symbol is a (readonly) parameter property declared in it, // then symbol is writeable here. - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -47944,6 +48767,7 @@ var ts; } return numberType; case 51 /* ExclamationToken */: + checkTruthinessExpression(node.operand); var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); return facts === 1048576 /* Truthy */ ? falseType : facts === 2097152 /* Falsy */ ? trueType : @@ -48053,19 +48877,20 @@ var ts; } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType) { + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { var properties = node.properties; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; } /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { var name = property.name; if (name.kind === 147 /* ComputedPropertyName */) { @@ -48074,20 +48899,10 @@ var ts; if (isComputedNonLiteralName(name)) { return undefined; } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || - getIndexTypeOfType(objectLiteralType, 0 /* String */); + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { - if (property.kind === 274 /* ShorthandPropertyAssignment */) { - return checkDestructuringAssignment(property, type); - } - else { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.initializer, type); - } + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); @@ -48111,6 +48926,23 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -48168,7 +49000,7 @@ var ts; } return undefined; } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; @@ -48191,7 +49023,7 @@ var ts; target = target.left; } if (target.kind === 186 /* ObjectLiteralExpression */) { - return checkObjectLiteralAssignment(target, sourceType); + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } if (target.kind === 185 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); @@ -48281,9 +49113,15 @@ var ts; function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + } + var leftType; + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); } - var leftType = checkExpression(left, checkMode); var rightType = checkExpression(right, checkMode); switch (operator) { case 39 /* AsteriskToken */: @@ -48405,7 +49243,7 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.getSpecialPropertyAssignmentKind(left.parent); + var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; checkSpecialAssignment(special, right); if (isJSSpecialPropertyAssignment(special)) { return leftType; @@ -48485,8 +49323,9 @@ var ts; } function isJSSpecialPropertyAssignment(special) { switch (special) { - case 1 /* ExportsProperty */: case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: case 5 /* Property */: case 6 /* Prototype */: case 3 /* PrototypeProperty */: @@ -48570,16 +49409,16 @@ var ts; // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. - var returnType = ts.getEffectiveReturnTypeNode(func); + var returnType = getReturnTypeFromAnnotation(func); if (returnType) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); } // Both yield and yield* expressions have type 'any' return anyType; } function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); + checkTruthinessExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -48592,7 +49431,7 @@ var ts; // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { - error(templateSpan.expression, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1, typeToString(esSymbolType), typeToString(stringType)); + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; @@ -48762,9 +49601,6 @@ var ts; node.contextualType = saveContextualType; return type; } - function checkExpresionNoReturn(node) { - checkExpression(node); - } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -48907,7 +49743,7 @@ var ts; checkSourceElement(node.default); var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } if (!hasNonCircularTypeParameterDefault(typeParameter)) { error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); @@ -48947,6 +49783,9 @@ var ts; if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } + if (func.kind === 195 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. @@ -48954,17 +49793,6 @@ var ts; error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - } - return -1; - } function checkTypePredicate(node) { var parent = getTypePredicateParent(node); if (!parent) { @@ -48988,8 +49816,7 @@ var ts; } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), // TODO: GH#18217 - node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -49110,7 +49937,7 @@ var ts; } } else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node); + checkAsyncFunctionReturnType(node, returnTypeNode); } } if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { @@ -49565,7 +50392,10 @@ var ts; } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, keyofConstraintType, node.typeParameter.constraint); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); } function checkTypeOperator(node) { checkGrammarTypeOperatorNode(node); @@ -49579,6 +50409,7 @@ var ts; grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); } function checkImportType(node) { checkSourceElement(node.argument); @@ -49866,7 +50697,7 @@ var ts; case 239 /* InterfaceDeclaration */: case 240 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return 2 /* ExportType */; case 242 /* ModuleDeclaration */: @@ -50065,16 +50896,15 @@ var ts; * Checks the return type of an async function to ensure it is a compatible * Promise implementation. * - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. * * @param node The signature to check */ - function checkAsyncFunctionReturnType(node) { + function checkAsyncFunctionReturnType(node, returnTypeNode) { // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -50099,30 +50929,29 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); // TODO: GH#18217 var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (returnType === errorType) { - return errorType; + return; } var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return errorType; + return; } } else { // Always mark the type node as referenced if it points to a value markTypeNodeAsReferenced(returnTypeNode); if (returnType === errorType) { - return errorType; + return; } var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === undefined) { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return errorType; + return; } var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; @@ -50133,28 +50962,27 @@ var ts; else { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); } - return errorType; + return; } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return errorType; + return; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } } - // Get and return the awaited type of the return type. - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } /** Check a decorator */ function checkDecorator(node) { @@ -50185,7 +51013,7 @@ var ts; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); // TODO: GH#18217 + var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; @@ -50309,9 +51137,13 @@ var ts; } } break; - case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: + var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 154 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); @@ -50351,6 +51183,13 @@ var ts; } checkSourceElement(node.typeExpression); } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } @@ -50445,14 +51284,11 @@ var ts; } var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function - var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ - ? checkAsyncFunctionReturnType(node) // Async function - : getTypeFromTypeNode(returnTypeNode)); // normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } - if (produceDiagnostics && !returnTypeNode) { + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { @@ -50465,6 +51301,13 @@ var ts; getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJavaScriptFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. @@ -50519,6 +51362,7 @@ var ts; case 163 /* FunctionType */: case 164 /* ConstructorType */: case 240 /* TypeAliasDeclaration */: + case 174 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -50529,7 +51373,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; @@ -50549,14 +51393,14 @@ var ts; } var symbol = getSymbolOfNode(member); if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; case 155 /* 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 */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } } break; @@ -50573,16 +51417,45 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { + if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + return; + if (node.kind === 174 /* InferType */) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + else { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; - if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol))); + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } function addToGroup(map, key, value, getKey) { var keyString = String(getKey(key)); var group = map.get(keyString); @@ -50633,7 +51506,7 @@ var ts; var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); if (parameter && name) { if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { @@ -50650,7 +51523,7 @@ var ts; (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { - addDiagnostic(0 /* Local */, unuseds.length === 1 + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); } @@ -50669,29 +51542,29 @@ var ts; addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - addDiagnostic(kind, bindingElements.length === 1 - ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); } } else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; - addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); } } }); unusedVariables.forEach(function (_a) { var declarationList = _a[0], declarations = _a[1]; if (declarationList.declarations.length === declarations.length) { - addDiagnostic(0 /* Local */, declarations.length === 1 + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var decl = declarations_5[_i]; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); } } }); @@ -50994,10 +51867,13 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + } } } } @@ -51118,7 +51994,7 @@ var ts; function checkIfStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); if (node.thenStatement.kind === 218 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); @@ -51129,14 +52005,21 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); checkSourceElement(node.statement); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); } function checkWhileStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.statement); } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 4096 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { @@ -51153,7 +52036,7 @@ var ts; } } if (node.condition) - checkExpression(node.condition); + checkTruthinessExpression(node.condition); if (node.incrementor) checkExpression(node.incrementor); checkSourceElement(node.statement); @@ -51557,10 +52440,6 @@ var ts; checkGrammarBreakOrContinueStatement(node); // TODO: Check that target label is valid } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 156 /* GetAccessor */ - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 157 /* SetAccessor */)) !== undefined; - } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function @@ -51600,7 +52479,7 @@ var ts; error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + else if (getReturnTypeFromAnnotation(func)) { if (functionFlags & 2 /* Async */) { // Async function var promisedType = getPromisedTypeOfPromise(returnType); var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -51909,8 +52788,9 @@ var ts; } // If the type parameter node does not have an identical constraint as the resolved // type parameter at this position, we report an error. - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); if (sourceConstraint) { // relax check if later interface augmentation has no constraint if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { @@ -52006,8 +52886,9 @@ var ts; // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52050,7 +52931,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_7 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52069,7 +52950,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_7(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -52829,9 +53710,9 @@ var ts; } else { // export * from "foo" - var moduleSymbol_2 = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol_2 && hasExportAssignmentSymbol(moduleSymbol_2)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol_2)); + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + 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 && moduleKind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768 /* ExportStar */); @@ -52922,9 +53803,9 @@ var ts; } } // Checks for export * conflicts - var exports_2 = getExportsOfModule(moduleSymbol); - if (exports_2) { - exports_2.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -53024,6 +53905,8 @@ var ts; case 169 /* OptionalType */: case 170 /* RestType */: return checkSourceElement(node.type); + case 176 /* ThisType */: + return checkThisType(node); case 177 /* TypeOperator */: return checkTypeOperator(node); case 173 /* ConditionalType */: @@ -53034,12 +53917,14 @@ var ts; return checkImportType(node); case 293 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 299 /* JSDocTypeTag */: + case 301 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 300 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: return checkJSDocParameterTag(node); case 287 /* JSDocFunctionType */: checkSignatureDeclaration(node); @@ -53252,10 +54137,7 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1 /* TypeChecked */)) { - // If skipLibCheck is enabled, skip type checking if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip type checking if file contains a - // '/// ' directive. - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + if (ts.skipTypeChecking(node, compilerOptions)) { return; } // Grammar checking @@ -53269,8 +54151,8 @@ var ts; registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { - if (unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { diagnostics.add(diag); } }); @@ -53349,6 +54231,7 @@ var ts; var symbols = ts.createSymbolTable(); var isStatic = false; populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword return symbolsToArray(symbols); function populateSymbols() { while (location) { @@ -53571,10 +54454,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 296 /* JSDocParameterTag */) { + if (entityName.parent.kind === 297 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 300 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -53643,7 +54526,7 @@ var ts; grandParent.kind === 182 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; } @@ -53727,7 +54610,7 @@ var ts; } if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { var containingClass = ts.getContainingClass(node); var classType = getTypeOfNode(containingClass); typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); @@ -53742,8 +54625,8 @@ var ts; // extends clause of a class. We handle that case here. var classNode = ts.getContainingClass(node); var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -53752,7 +54635,7 @@ var ts; } if (isTypeDeclarationName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } if (ts.isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -53761,10 +54644,10 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); + return symbol ? getTypeOfSymbol(symbol) : errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -54382,7 +55265,8 @@ var ts; setAccessor: setAccessor, getAccessor: getAccessor }; - } + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55493,9 +56377,6 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - if (node.name.kind === 183 /* ArrayBindingPattern */ || node.name.kind === 182 /* ObjectBindingPattern */) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (node.propertyName) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); } @@ -55767,10 +56648,10 @@ var ts; // this has already been reported, and don't report if it has. // if (node.parent.kind === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { - var links_1 = getNodeLinks(node.parent); + var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); } } else { @@ -56902,19 +57783,7 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - 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; - } + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters @@ -57026,17 +57895,7 @@ var ts; return node; } ts.createConditional = createConditional; - 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]; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue @@ -57839,7 +58698,7 @@ var ts; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -57855,7 +58714,7 @@ var ts; function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(260 /* JsxOpeningElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -58150,7 +59009,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(304 /* NotEmittedStatement */); + var node = createSynthesizedNode(305 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -58162,7 +59021,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(308 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -58174,7 +59033,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(307 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -58189,7 +59048,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(305 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -58205,7 +59064,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 306 /* CommaListExpression */) { + if (node.kind === 307 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -58215,7 +59074,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(306 /* CommaListExpression */); + var node = createSynthesizedNode(307 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -59385,6 +60244,11 @@ var ts; var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1 /* LessThan */: @@ -59527,11 +60391,15 @@ var ts; */ function parenthesizeDefaultExpression(e) { var check = ts.skipPartiallyEmittedExpressions(e); - return check.kind === 207 /* ClassExpression */ || - check.kind === 194 /* FunctionExpression */ || - isCommaSequence(check) - ? ts.createParen(e) - : e; + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; } ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; /** @@ -59684,6 +60552,9 @@ var ts; case 203 /* ConditionalExpression */: node = node.condition; continue; + case 191 /* TaggedTemplateExpression */: + node = node.tag; + continue; case 189 /* CallExpression */: if (stopAtCallExpressions) { return node; @@ -59693,7 +60564,7 @@ var ts; case 188 /* ElementAccessExpression */: case 187 /* PropertyAccessExpression */: case 211 /* NonNullExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -59709,7 +60580,7 @@ var ts; ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || - node.kind === 306 /* CommaListExpression */; + node.kind === 307 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -59728,7 +60599,7 @@ var ts; case 210 /* AsExpression */: case 211 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -59765,7 +60636,7 @@ var ts; case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 305 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -60042,7 +60913,7 @@ var ts; // `1` in `let { 1: b } = ...` if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -60054,7 +60925,7 @@ var ts; // `1` in `({ 1: b } = ...)` if (bindingElement.name) { var propertyName = bindingElement.name; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -60065,13 +60936,18 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) ? target.expression : target; } ts.Debug.fail("Invalid property name for binding element."); } ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } /** * Gets the elements of a BindingOrAssignmentPattern */ @@ -60555,9 +61431,9 @@ var ts; case 277 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -60613,7 +61489,7 @@ var ts; case 218 /* EmptyStatement */: case 208 /* OmittedExpression */: case 234 /* DebuggerStatement */: - case 304 /* NotEmittedStatement */: + case 305 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -60992,10 +61868,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -61009,8 +61885,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) - : ts.prependStatements(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -61188,7 +62064,7 @@ var ts; function decode(host, mapPath, map, program, fallbackCache) { if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot || currentDirectory; + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; var decodedMappings; var generatedOrderedMappings; var sourceOrderedMappings; @@ -61223,10 +62099,11 @@ var ts; } function getSourceFileLike(fileName, location) { // Lookup file in program, if provided - var file = program && program.getSourceFile(fileName); - if (!file) { + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + var file = program && program.getSourceFile(path); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (!file || file.resolvedPath !== path) { // Otherwise check the cache (which may hit disk) - var path = ts.toPath(fileName, location, host.getCanonicalFileName); return fallbackCache.get(path); } return file; @@ -62062,7 +62939,7 @@ var ts; var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); return ts.createElementAccess(value, argumentExpression); } - else if (ts.isStringOrNumericLiteral(propertyName)) { + else if (ts.isStringOrNumericLiteralLike(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); @@ -62742,7 +63619,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, context.endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -63194,6 +64071,7 @@ var ts; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); statements.push(statement); } } @@ -63211,6 +64089,7 @@ var ts; ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); expressions.push(expression); } return expressions; @@ -63631,6 +64510,11 @@ var ts; } return false; } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } /** * Serializes the type of a node for use with decorator type metadata. * @@ -63640,10 +64524,10 @@ var ts; switch (node.kind) { case 152 /* PropertyDeclaration */: case 149 /* Parameter */: - case 156 /* GetAccessor */: return serializeTypeNode(node.type); case 157 /* SetAccessor */: - return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 156 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 154 /* MethodDeclaration */: @@ -63834,11 +64718,11 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: - var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); + return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); case ts.TypeReferenceSerializationKind.BooleanType: @@ -63863,14 +64747,35 @@ var ts; return ts.Debug.assertNever(kind); } } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 71 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 71 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } /** * Serializes an entity name as an expression for decorator type metadata. * * @param node The entity name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * entity name at runtime. */ - function serializeEntityNameAsExpression(node, useFallback) { + function serializeEntityNameAsExpression(node) { switch (node.kind) { case 71 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were @@ -63879,12 +64784,9 @@ var ts; name.flags &= ~8 /* Synthesized */; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. - if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); - } return name; case 146 /* QualifiedName */: - return serializeQualifiedNameAsExpression(node, useFallback); + return serializeQualifiedNameAsExpression(node); } } /** @@ -63894,19 +64796,8 @@ var ts; * @param useFallback A value indicating whether to use logical operators to test for the * qualified name at runtime. */ - function serializeQualifiedNameAsExpression(node, useFallback) { - var left; - if (node.left.kind === 71 /* Identifier */) { - left = serializeEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); - } - else { - left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); - } - return ts.createPropertyAccess(left, node.right); + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); } /** * Gets an expression that points to the global "Symbol" constructor at runtime if it is @@ -64315,7 +65206,8 @@ var ts; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; @@ -64350,8 +65242,13 @@ var ts; /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } ts.setTextRange(enumStatement, node); - ts.setEmitFlags(enumStatement, emitFlags); + ts.addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); // Add a DeclarationMarker for the enum to preserve trailing comments and mark // the end of the declaration. @@ -64369,7 +65266,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -64498,7 +65395,7 @@ var ts; // })(m1 || (m1 = {})); // trailing comment module // ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(statement); return true; } @@ -64533,7 +65430,8 @@ var ts; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; @@ -64567,8 +65465,13 @@ var ts; /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } ts.setTextRange(moduleStatement, node); - ts.setEmitFlags(moduleStatement, emitFlags); + ts.addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); // Add a DeclarationMarker for the namespace to preserve trailing comments and mark // the end of the declaration. @@ -64610,7 +65513,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -65420,7 +66323,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -66027,7 +66930,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -66055,7 +66958,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependStatements(statements, leadingStatements); + ts.addStatementsAfterPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -67150,7 +68053,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -67405,7 +68308,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -67518,7 +68421,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -67628,7 +68531,7 @@ var ts; return 2 /* ReplaceWithReturn */; } // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis(), firstStatement); + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); // If we're actually replacing the original statement, we need to signal this to the caller. if (superCallExpression) { return 1 /* ReplaceSuperCapture */; @@ -67820,7 +68723,7 @@ var ts; captureThisForNode(statements, node, ts.createThis()); } } - function captureThisForNode(statements, node, initializer, originalStatement) { + function captureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -67828,7 +68731,6 @@ var ts; /*type*/ undefined, initializer) ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); - ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); } @@ -68158,7 +69060,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependStatements(statements, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { @@ -68420,7 +69322,7 @@ var ts; var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) - : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement), node, convertedLoopState && resetLabel); + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { @@ -68737,7 +69639,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependStatements(statements_4, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -70412,7 +71314,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -72650,7 +73552,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -72873,7 +73775,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -72936,9 +73838,9 @@ var ts; return visitFunctionDeclaration(node); case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 307 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 308 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -73164,7 +74066,7 @@ var ts; if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { // import "mod"; - return ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); } else { var variables = []; @@ -73185,18 +74087,20 @@ var ts; /*type*/ undefined, ts.getGeneratedNameForNode(node))); } } - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), - /*location*/ node)); + /*location*/ node), + /*original*/ node)); } } else if (namespaceDeclaration && ts.isDefaultImport(node)) { // import d, * as n from "mod"; statements = ts.append(statements, ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node)), - /*location*/ node) + /*location*/ node), + /*original*/ node) ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -73232,20 +74136,20 @@ var ts; var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); } else { - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), /*type*/ undefined, createRequireCall(node)) ], - /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node)); + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); } } else { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); } } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -73274,23 +74178,24 @@ var ts; var statements = []; // export { x, y } from "mod"; if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.setTextRange(ts.createVariableStatement( + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(generatedName, /*type*/ undefined, createRequireCall(node)) ])), - /*location*/ node)); + /*location*/ node), + /* original */ node)); } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); } return ts.singleOrMany(statements); } else { // export * from "mod"; - return ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); } } /** @@ -73396,7 +74301,7 @@ var ts; statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); } if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); } } else { @@ -74142,7 +75047,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -74870,9 +75775,9 @@ var ts; return visitCatchClause(node); case 216 /* Block */: return visitBlock(node); - case 307 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 308 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -75916,7 +76821,8 @@ var ts; 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | - 4 /* GenerateNamesForShadowedTypeParams */; + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; /** * Transforms a ts file into a .d.ts file * This process requires type information, which is retrieved through the emit resolver. Because of this, @@ -75936,6 +76842,7 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, @@ -75944,6 +76851,7 @@ var ts; reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode }; var errorNameNode; var currentSourceFile; @@ -76002,6 +76910,11 @@ var ts; } } } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } function trackSymbol(symbol, enclosingDeclaration, meaning) { if (symbol.flags & 262144 /* TypeParameter */) return; @@ -76029,7 +76942,7 @@ var ts; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; - var refs_1 = ts.createMap(); + refs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) @@ -76043,7 +76956,7 @@ var ts; getSymbolAccessibilityDiagnostic = throwDiagnostic; needsScopeFixMarker = false; resultHasScopeMarker = false; - collectReferences(sourceFile, refs_1); + collectReferences(sourceFile, refs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -76064,7 +76977,7 @@ var ts; bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); - refs_1.forEach(referenceVisitor_1); + refs.forEach(referenceVisitor_1); return bundle; } // Single source file @@ -76092,6 +77005,7 @@ var ts; combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; function getFileReferencesForUsedTypeReferences() { return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; @@ -76309,10 +77223,18 @@ var ts; if (!input) return undefined; // TODO: GH#18217 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); - if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { - var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); - if (newName) { - return ts.createLiteral(newName); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } } } return input; @@ -76841,6 +77763,15 @@ var ts; } return false; } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } function ensureModifiers(node, privateDeclaration) { var currentFlags = ts.getModifierFlags(node); var newFlags = ensureModifierFlags(node, privateDeclaration); @@ -76854,7 +77785,7 @@ var ts; var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; var parentIsFile = node.parent.kind === 277 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { - mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; } return maskModifierFlags(node, mask, additions); @@ -76873,7 +77804,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_8 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -76887,7 +77818,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_8(range); } } return prop; @@ -76913,6 +77844,11 @@ var ts; if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) } @@ -77049,7 +77985,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(309 /* Count */); + var enabledSyntaxKindFeatures = new Array(310 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -77396,7 +78332,7 @@ var ts; if (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { // The relative paths are relative to the common directory @@ -77602,7 +78538,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 304 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -77619,7 +78555,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 304 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -77798,7 +78734,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 304 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -77812,10 +78748,12 @@ var ts; var savedContainerPos = containerPos; var savedContainerEnd = containerEnd; var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments) { + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. containerPos = pos; } - if (!skipTrailingComments) { + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end @@ -78164,17 +79102,17 @@ var ts; if (sourceFile.kind === 278 /* Bundle */) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error var isJs = ts.isSourceFileJavaScript(sourceFile); - var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } @@ -78229,6 +79167,7 @@ var ts; }); var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; + var exportedModulesFromDeclarationEmit; // Emit each output file ts.performance.mark("beforePrint"); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); @@ -78238,6 +79177,7 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -78296,7 +79236,7 @@ var ts; // Setup and perform the transformation to retrieve declarations from the input files var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; - if (emitOnlyDtsFiles && !compilerOptions.declaration) { + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. // Do that here when emitting only dts files nonJsFiles.forEach(collectLinkedAliases); @@ -78325,6 +79265,10 @@ var ts; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } } declarationTransform.dispose(); } @@ -78963,9 +79907,9 @@ var ts; case 262 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return emitCommaList(node); } } @@ -81680,7 +82624,7 @@ var ts; case WatchLogLevel.TriggerOnly: return createFileWatcherWithTriggerLogging; case WatchLogLevel.Verbose: - return createFileWatcherWithLogging; + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; } } function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { @@ -81693,9 +82637,27 @@ var ts; } }; } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { return addWatch(host, file, function (fileName, cbOptional) { - var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); log(triggerredInfo); var start = ts.timestamp(); cb(fileName, cbOptional, passThrough); @@ -81825,7 +82787,7 @@ var ts; } } ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82187,6 +83149,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -82224,7 +83187,8 @@ var ts; var packageIdToSourceFile = ts.createMap(); // Maps from a SourceFile's `.path` to the name of the package it was imported with. var sourceFileToPackageName = ts.createMap(); - var redirectTargetsSet = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -82331,7 +83295,7 @@ var ts; getSourceFileFromReference: getSourceFileFromReference, getLibFileFromReference: getLibFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsMap: redirectTargetsMap, isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -82617,7 +83581,7 @@ var ts; fileChanged = false; newSourceFile = oldSourceFile; // Use the redirect. } - else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { // If a redirected-to source file changes, the redirect may be broken. if (newSourceFile !== oldSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -82746,7 +83710,7 @@ var ts; resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; - redirectTargetsSet = oldProgram.redirectTargetsSet; + redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -82938,10 +83902,7 @@ var ts; } function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { - // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a - // '/// ' directive. - if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { + if (ts.skipTypeChecking(sourceFile, options)) { return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); @@ -83335,7 +84296,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -83413,9 +84374,17 @@ var ts; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path - // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } } // If the file was previously found via a node_modules search, but is now being processed as a root file, // then everything it sucks in may also be marked incorrectly, and needs to be checked again. @@ -83468,7 +84437,7 @@ var ts; // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 - redirectTargetsSet.set(fileFromPackageId.path, true); + redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); @@ -83698,7 +84667,7 @@ var ts; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); allFilesBelongToPath = false; } } @@ -83715,6 +84684,7 @@ var ts; if (sourceFile === undefined) { return undefined; } + sourceFile.path = toPath(refPath); var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } @@ -83728,7 +84698,7 @@ var ts; ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 } function verifyCompilerOptions() { - if (options.strictPropertyInitialization && !options.strictNullChecks) { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { @@ -83788,14 +84758,14 @@ var ts; if (options.composite && rootNames.length < files.length) { var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_10 = function (file) { + var _loop_9 = function (file) { if (normalizedRootNames.every(function (r) { return r !== file; })) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); } }; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var file = sourceFiles_4[_i]; - _loop_10(file); + _loop_9(file); } } if (options.paths) { @@ -83852,7 +84822,7 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } - if (options.declarationMap && !options.declaration) { + if (options.declarationMap && !ts.getEmitDeclarations(options)) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); } if (options.lib && options.noLib) { @@ -83893,6 +84863,10 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } + // Any emit other than common js is error + else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + } } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted @@ -84024,12 +84998,12 @@ var ts; } function createDiagnosticForReference(index, message, arg0, arg1) { var referencesSyntax = getProjectReferencesSyntax(); - if (referencesSyntax) { - if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { - return; - } + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); @@ -84079,14 +85053,6 @@ var ts; } return !!props.length; } - function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { - if (arrayLiteral.elements.length <= index) { - // Out-of-bounds - return false; - } - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); - return false; // TODO: GH#18217 This function always returns `false`!` - } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -84139,7 +85105,8 @@ var ts; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; /** - * Returns the target config filename of a project reference + * Returns the target config filename of a project reference. + * Note: The file might not exist. */ function resolveProjectReferencePath(host, ref) { if (!host.fileExists(ref.path)) { @@ -84159,7 +85126,6 @@ var ts; switch (extension) { case ".ts" /* Ts */: case ".d.ts" /* Dts */: - case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check // These are always allowed. return undefined; case ".tsx" /* Tsx */: @@ -84168,6 +85134,8 @@ var ts; return needJsx() || needAllowJs(); case ".js" /* Js */: return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); } function needJsx() { return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; @@ -84175,6 +85143,9 @@ var ts; function needAllowJs() { return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } } ts.getResolutionDiagnostic = getResolutionDiagnostic; function getModuleNames(_a) { @@ -84196,7 +85167,7 @@ var ts; function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -84207,6 +85178,22 @@ var ts; (function (ts) { var BuilderState; (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.path; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -84219,12 +85206,9 @@ var ts; var checker = program.getTypeChecker(); for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); } } } @@ -84269,6 +85253,7 @@ var ts; function create(newProgram, getCanonicalFileName, oldState) { var fileInfos = ts.createMap(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; var hasCalledUpdateShapeSignature = ts.createMap(); var useOldState = canReuseOldState(referencedMap, oldState); // Create the reference map, and set the file infos @@ -84281,12 +85266,20 @@ var ts; if (newReferences) { referencedMap.set(sourceFile.path, newReferences); } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } } fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); } return { fileInfos: fileInfos, referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, allFilesExcludingDefaultLibraryFile: undefined, allFileNames: undefined @@ -84296,7 +85289,7 @@ var ts; /** * Gets the files affected by the path from the program */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { // Since the operation could be cancelled, the signatures are always stored in the cache // They will be commited once it is safe to use them // eg when calling this api from tsserver, if there is no cancellation of the operation @@ -84306,10 +85299,10 @@ var ts; if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); if (!cacheToUpdateSignature) { // Commit all the signatures in the signature cache updateSignaturesFromCache(state, signatureCache); @@ -84331,8 +85324,9 @@ var ts; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { return false; @@ -84349,6 +85343,9 @@ var ts; var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } } else { latestSignature = prevSignature; // TODO: GH#18217 @@ -84357,6 +85354,44 @@ var ts; cacheToUpdateSignature.set(sourceFile.path, latestSignature); return !prevSignature || latestSignature !== prevSignature; } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -84466,7 +85501,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -84486,7 +85521,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 queue, getReferencedByPaths(state, currentPath)); } @@ -84517,7 +85552,8 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -84553,6 +85589,10 @@ var ts; var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); } } }); @@ -84574,14 +85614,14 @@ var ts; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { - var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var seenAffectedFiles = state.seenAffectedFiles; var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 while (affectedFilesIndex < affectedFiles.length) { var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.path)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - semanticDiagnosticsPerFile.delete(affectedFile.path); + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); return affectedFile; } seenAffectedFiles.set(affectedFile.path, true); @@ -84593,6 +85633,7 @@ var ts; // Commit the changes in file signature ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); state.affectedFiles = undefined; } // Get next changed file @@ -84610,13 +85651,66 @@ var ts; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; - state.semanticDiagnosticsPerFile.delete(nextKey.value); state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return false; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } /** * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly @@ -84883,6 +85977,7 @@ var ts; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -84940,6 +86035,7 @@ var ts; function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); @@ -84979,17 +86075,19 @@ var ts; perDirectoryResolvedModuleNames.clear(); nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); - clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); @@ -85041,7 +86139,7 @@ var ts; perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); - watchFailedLookupLocationOfResolution(resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } @@ -85137,14 +86235,23 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - // Always watch root directory recursively - return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, "/node_modules/")) { + while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } @@ -85173,16 +86280,25 @@ var ts; function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); } - function watchFailedLookupLocationOfResolution(resolution) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { // No need to set the resolution refCount - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { - return; - } - if (resolution.refCount !== undefined) { - resolution.refCount++; - return; + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } } - resolution.refCount = 1; + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); var failedLookupLocations = resolution.failedLookupLocations; var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { @@ -85197,6 +86313,7 @@ var ts; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); } if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); setAtRoot = true; } else { @@ -85205,10 +86322,19 @@ var ts; } } if (setAtRoot) { - // This is always recursive - setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { @@ -85220,7 +86346,7 @@ var ts; } } function stopWatchFailedLookupLocationOfResolution(resolution) { - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + if (!resolution.refCount) { return; } resolution.refCount--; @@ -85443,23 +86569,36 @@ var ts; } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); -// Used by importFixes to synthesize import module specifiers. +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { // Note: importingSourceFile is just for usesJsExtensionOnImports - function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences) { + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, toFileName, info.getCanonicalFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { + var isBundle = (compilerOptions.out || compilerOptions.outFile); + if (isBundle && host.getCommonSourceDirectory) { + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); + } + var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; + return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + } + moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) return [[ambient]]; @@ -85467,7 +86606,8 @@ var ts; if (!files) { return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); } - var modulePaths = getAllModulePaths(files, ts.getSourceFileOfNode(moduleSymbol.valueDeclaration).fileName, info.getCanonicalFileName, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); @@ -85552,64 +86692,66 @@ var ts; return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; }) || false; } - function discoverProbableSymlinks(files, getCanonicalFileName, host) { + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); var symlinks = ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; }); }); - var result = ts.createMap(); - if (symlinks) { - var currentDirectory = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { - var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; - var resolvedParts = ts.getPathComponents(ts.toPath(resolvedPath, currentDirectory, getCanonicalFileName)); - var originalParts = ts.getPathComponents(ts.toPath(originalPath, currentDirectory, getCanonicalFileName)); - while (compareStrings(resolvedParts[resolvedParts.length - 1], originalParts[originalParts.length - 1]) === 0 /* EqualTo */) { - resolvedParts.pop(); - originalParts.pop(); - } - result.set(ts.getPathFromPathComponents(originalParts), ts.getPathFromPathComponents(resolvedParts)); - } + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); } return result; } - function getAllModulePathsUsingIndirectSymlinks(files, target, getCanonicalFileName, host) { - var links = discoverProbableSymlinks(files, getCanonicalFileName, host); - var paths = ts.arrayFrom(links.keys()); - var options; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, paths_2 = paths; _i < paths_2.length; _i++) { - var path = paths_2[_i]; - var resolved = links.get(path); - if (compareStrings(target.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */) { - var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - if (!options) - options = []; - options.push(option); - } - } - } - if (options) { - options.push(target); // Since these are speculative, we also include the original resolved name as a possibility - return options; - } - return [target]; - } /** * Looks for existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(files, importedFileName, getCanonicalFileName, host) { - var symlinks = ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === importedFileName ? res.originalPath : undefined; - }); + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } }); - return symlinks.length === 0 ? getAllModulePathsUsingIndirectSymlinks(files, ts.getNormalizedAbsolutePath(importedFileName, host.getCurrentDirectory ? host.getCurrentDirectory() : ""), getCanonicalFileName, host) : symlinks; + result.push.apply(result, targets); + return result; } function getRelativePathNParents(relativePath) { var components = ts.getPathComponents(relativePath); @@ -85622,8 +86764,8 @@ var ts; return components.length - 1; } function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { return decl.name.text; } } @@ -85633,10 +86775,7 @@ var ts; var patternText_1 = _a[_i]; var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { + if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && @@ -85749,7 +86888,7 @@ var ts; partEnd = fullPath.indexOf("/", partStart + 1); switch (state) { case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { topLevelNodeModulesIndex = partStart; topLevelPackageNameIndex = partEnd; state = 1 /* NodeModules */; @@ -85766,7 +86905,7 @@ var ts; } break; case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { state = 1 /* NodeModules */; } else { @@ -85951,6 +87090,7 @@ var ts; createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; } var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); @@ -86079,16 +87219,15 @@ var ts; }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); - if (configFileName) { + if (configFileName && !host.configFileParsingResult) { newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); - if (host.configFileParsingResult) { - setConfigFileParsingResult(host.configFileParsingResult); - } - else { - ts.Debug.assert(!rootFileNames); - parseConfigFile(); - } + ts.Debug.assert(!rootFileNames); + parseConfigFile(); newLine = updateNewLine(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); @@ -86636,7 +87775,7 @@ var ts; } var outputs = []; outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); - if (configFile.options.declaration && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); if (configFile.options.declarationMap) { @@ -86651,7 +87790,7 @@ var ts; } var outputs = []; outputs.push(project.options.outFile); - if (project.options.declaration) { + if (ts.getEmitDeclarations(project.options)) { var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { @@ -86803,6 +87942,7 @@ var ts; return builder.cleanAllProjects(); } if (watch) { + builder.buildAllProjects(); builder.startWatching(); return undefined; } @@ -86859,7 +87999,7 @@ var ts; // Everything is broken - we don't even know what to watch. Give up. return; } - var _loop_11 = function (resolved) { + var _loop_10 = function (resolved) { var cfg = configFileCache.parseConfigFile(resolved); if (cfg) { // Watch this file @@ -86886,7 +88026,7 @@ var ts; }; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var resolved = _a[_i]; - _loop_11(resolved); + _loop_10(resolved); } function invalidateProjectAndScheduleBuilds(resolved) { invalidateProject(resolved); @@ -87056,7 +88196,7 @@ var ts; }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { resultFlags |= BuildResultFlags.SyntaxErrors; for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { @@ -87067,7 +88207,7 @@ var ts; return resultFlags; } // Don't emit .d.ts if there are decl file errors - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { resultFlags |= BuildResultFlags.DeclarationEmitErrors; @@ -87121,15 +88261,16 @@ var ts; if (context.options.dry) { return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) + if (context.options.verbose) { buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { var file = outputs_1[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file)); + priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); } compilerHost.setModifiedTime(file, now); } @@ -87327,7 +88468,7 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile); + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; if (inputTime > newestInputFileTime) { newestInputFileName = inputFile; newestInputFileTime = inputTime; @@ -87356,7 +88497,7 @@ var ts; missingOutputFileName = output; break; } - var outputTime = host.getModifiedTime(output); + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; if (outputTime < oldestOutputFileTime) { oldestOutputFileTime = outputTime; oldestOutputFileName = output; @@ -87381,7 +88522,8 @@ var ts; newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } else { - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, host.getModifiedTime(output)); + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } @@ -87500,7 +88642,7 @@ var ts; // Don't report status on "solution" projects break; default: - ts.assertTypeIsNever(status); + ts.assertType(status); } } ts.formatUpToDateStatus = formatUpToDateStatus; @@ -88200,7 +89342,7 @@ var ts; case 240 /* TypeAliasDeclaration */: case 166 /* TypeLiteral */: return 2 /* Type */; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; case 276 /* EnumMember */: @@ -88328,16 +89470,20 @@ var ts; return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 189 /* CallExpression */); + return isCallOrNewExpressionTargetWorker(node, ts.isCallExpression); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 190 /* NewExpression */); + return isCallOrNewExpressionTargetWorker(node, ts.isNewExpression); } ts.isNewExpressionTarget = isNewExpressionTarget; - function isCallOrNewExpressionTarget(node, kind) { + function isCallOrNewExpressionTarget(node) { + return isCallOrNewExpressionTargetWorker(node, ts.isCallOrNewExpression); + } + ts.isCallOrNewExpressionTarget = isCallOrNewExpressionTarget; + function isCallOrNewExpressionTargetWorker(node, pred) { var target = climbPastPropertyAccess(node); - return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && pred(target.parent) && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -88451,7 +89597,7 @@ var ts; case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; case 240 /* TypeAliasDeclaration */: case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return "type" /* typeElement */; case 241 /* EnumDeclaration */: return "enum" /* enumElement */; case 235 /* VariableDeclaration */: @@ -88502,7 +89648,7 @@ var ts; case 6 /* Prototype */: return "local class" /* localClassElement */; default: { - ts.assertTypeIsNever(kind); + ts.assertType(kind); return "" /* unknown */; } } @@ -88780,7 +89926,7 @@ var ts; var current = sourceFile; outer: while (true) { // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { var child = _a[_i]; var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { @@ -88991,7 +90137,21 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(tokenIn, sourceFile) { + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { var token = tokenIn; // This function determines if the node could be type argument position // Since during editing, when type argument list is not complete, @@ -89071,7 +90231,7 @@ var ts; } return undefined; } - ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; /** * Returns true if the cursor at position in sourceFile is within a comment. * @@ -89203,6 +90363,10 @@ var ts; return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { return ts.createTextSpanFromBounds(range.pos, range.end); } @@ -89222,6 +90386,7 @@ var ts; ts.typeKeywords = [ 119 /* AnyKeyword */, 122 /* BooleanKeyword */, + 86 /* FalseKeyword */, 128 /* KeyOfKeyword */, 131 /* NeverKeyword */, 95 /* NullKeyword */, @@ -89229,6 +90394,7 @@ var ts; 135 /* ObjectKeyword */, 137 /* StringKeyword */, 138 /* SymbolKeyword */, + 101 /* TrueKeyword */, 105 /* VoidKeyword */, 140 /* UndefinedKeyword */, 141 /* UniqueKeyword */, @@ -89240,8 +90406,7 @@ var ts; ts.isTypeKeyword = isTypeKeyword; /** True if the symbol is for an external module, as opposed to a namespace. */ function isExternalModuleSymbol(moduleSymbol) { - ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); - return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; function nodeSeenTracker() { @@ -89265,13 +90430,13 @@ var ts; } ts.repeatString = repeatString; function skipConstraint(type) { - return type.isTypeParameter() ? type.getConstraint() : type; // TODO: GH#18217 + return type.isTypeParameter() ? type.getConstraint() || type : type; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { return name.kind === 147 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal - ? ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined + ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.getTextOfIdentifierOrLiteral(name); } ts.getNameFromPropertyName = getNameFromPropertyName; @@ -89326,6 +90491,14 @@ var ts; } } ts.getQuotePreference = getQuotePreference; + function getQuoteFromPreference(qp) { + switch (qp) { + case 0 /* Single */: return "'"; + case 1 /* Double */: return '"'; + default: return ts.Debug.assertNever(qp); + } + } + ts.getQuoteFromPreference = getQuoteFromPreference; function symbolNameNoDefault(symbol) { var escaped = symbolEscapedNameNoDefault(symbol); return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); @@ -89383,56 +90556,6 @@ var ts; return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; } ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; - var NodeSet = /** @class */ (function () { - function NodeSet() { - this.map = ts.createMap(); - } - NodeSet.prototype.add = function (node) { - this.map.set(String(ts.getNodeId(node)), node); - }; - NodeSet.prototype.has = function (node) { - return this.map.has(String(ts.getNodeId(node))); - }; - NodeSet.prototype.forEach = function (cb) { - this.map.forEach(cb); - }; - NodeSet.prototype.some = function (pred) { - return ts.forEachEntry(this.map, pred) || false; - }; - return NodeSet; - }()); - ts.NodeSet = NodeSet; - var NodeMap = /** @class */ (function () { - function NodeMap() { - this.map = ts.createMap(); - } - NodeMap.prototype.get = function (node) { - var res = this.map.get(String(ts.getNodeId(node))); - return res && res.value; - }; - NodeMap.prototype.getOrUpdate = function (node, setValue) { - var res = this.get(node); - if (res) - return res; - var value = setValue(); - this.set(node, value); - return value; - }; - NodeMap.prototype.set = function (node, value) { - this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); - }; - NodeMap.prototype.has = function (node) { - return this.map.has(String(ts.getNodeId(node))); - }; - NodeMap.prototype.forEach = function (cb) { - this.map.forEach(function (_a) { - var node = _a.node, value = _a.value; - return cb(value, node); - }); - }; - return NodeMap; - }()); - ts.NodeMap = NodeMap; function getParentNodeInSpan(node, file, span) { if (!node) return undefined; @@ -89463,6 +90586,14 @@ var ts; } } ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -89473,13 +90604,24 @@ var ts; ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios var displayParts; var lineStart; var indent; + var length; resetWriter(); var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { - displayParts: function () { return displayParts; }, + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, @@ -89508,23 +90650,35 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { + if (length > absoluteMaximumLength) + return; if (lineStart) { var indentString = ts.getIndentString(indent); if (indentString) { + length += indentString.length; displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); } lineStart = false; } } function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(displayPart(text, kind)); } function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(symbolPart(text, symbol)); } function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; displayParts.push(lineBreakPart()); lineStart = true; } @@ -89532,6 +90686,7 @@ var ts; displayParts = []; lineStart = true; indent = 0; + length = 0; } } function symbolPart(text, symbol) { @@ -89725,8 +90880,30 @@ var ts; return clone; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; - function getSynthesizedDeepCloneWorker(node) { - var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); + function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone; + if (node && ts.isIdentifier(node) && renameMap && checker) { + var symbol = checker.getSymbolAtLocation(node); + var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); + if (renameInfo) { + clone = ts.createIdentifier(renameInfo.text); + } + } + if (!clone) { + clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + } + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + if (callback && node) + callback(node, clone); + return clone; + } + ts.getSynthesizedDeepCloneWithRenames = getSynthesizedDeepCloneWithRenames; + function getSynthesizedDeepCloneWorker(node, renameMap, checker, callback) { + var visited = (renameMap || checker || callback) ? + ts.visitEachChild(node, wrapper, ts.nullTransformationContext) : + ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. var clone_7 = ts.getSynthesizedClone(node); @@ -89743,6 +90920,9 @@ var ts; // would have made. visited.parent = undefined; return visited; + function wrapper(node) { + return getSynthesizedDeepCloneWithRenames(node, /*includeTrivia*/ true, renameMap, checker, callback); + } } function getSynthesizedDeepClones(nodes, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = true; } @@ -90497,18 +91677,18 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 297 /* JSDocReturnTag */: + case 298 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -90881,7 +92061,7 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_12 = function (name, kind) { + var _loop_11 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind)); @@ -90889,7 +92069,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_12(name, kind); + _loop_11(name, kind); } } } @@ -90905,7 +92085,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_13 = function (moduleName) { + var _loop_12 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); @@ -90913,7 +92093,7 @@ var ts; }; for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { var moduleName = _f[_e]; - _loop_13(moduleName); + _loop_12(moduleName); } } if (!foundGlobal) { @@ -91170,6 +92350,19 @@ var ts; (function (ts) { var Completions; (function (Completions) { + var SymbolOriginInfoKind; + (function (SymbolOriginInfoKind) { + SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 0] = "ThisType"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 1] = "SymbolMemberNoExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 2] = "SymbolMemberExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 3] = "Export"; + })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); + function originIsSymbolMember(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 1 /* SymbolMemberNoExport */; + } + function originIsExport(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 3 /* Export */; + } var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; @@ -91193,8 +92386,8 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) - return undefined; // TODO: GH#18217 + if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined @@ -91258,20 +92451,22 @@ var ts; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; - if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { + if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
- // The completion list at "1" will contain "div" with type any + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, - entries: [{ - name: tagName.getFullText(), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: "0", - }] }; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { @@ -91340,12 +92535,12 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (origin && origin.type === "this-type") { + if (origin && origin.kind === 0 /* ThisType */) { insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. - else if ((origin && origin.type === "symbol-member" || needsConvertPropertyAccess) && propertyAccessToConvert) { + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); // If the text after the '.' starts with this name, write over it. Else, add new text. @@ -91376,7 +92571,7 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(!!origin && origin.type === "export"), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), insertText: insertText, replacementSpan: replacementSpan, @@ -91402,7 +92597,7 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); @@ -91483,6 +92678,8 @@ var ts; return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case 171 /* UnionType */: + return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; default: return undefined; } @@ -91599,7 +92796,7 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -91634,7 +92831,7 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -91677,14 +92874,14 @@ var ts; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; } - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, allSourceFiles, preferences) { + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo || symbolOriginInfo.type !== "export") { + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { return { codeActions: undefined, sourceDisplay: undefined }; } var moduleSymbol = symbolOriginInfo.moduleSymbol; var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, allSourceFiles, formatContext, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { @@ -91833,7 +93030,7 @@ var ts; currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 302 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 303 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -91890,6 +93087,9 @@ var ts; case 146 /* QualifiedName */: node = parent.left; break; + case 242 /* ModuleDeclaration */: + node = parent.name; + break; case 181 /* ImportType */: case 212 /* MetaProperty */: node = parent; @@ -91996,11 +93196,11 @@ var ts; return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: - case 297 /* JSDocReturnTag */: - case 299 /* JSDocTypeTag */: - case 301 /* JSDocTypedefTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: + case 298 /* JSDocReturnTag */: + case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypedefTag */: return true; default: return false; @@ -92013,8 +93213,11 @@ var ts; var isImportType = ts.isLiteralImportTypeNode(node); var isTypeLocation = insideJsDocTagTypeExpression || (isImportType && !node.isTypeOf) || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); - var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile)); + var allowTypeOrValue = isRhsOfImportDeclaration || (!isTypeLocation && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker)); if (ts.isEntityName(node) || isImportType) { + var isNamespaceName = ts.isModuleDeclaration(node.parent); + if (isNamespaceName) + isNewIdentifierLocation = true; var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { symbol = ts.skipAlias(symbol, typeChecker); @@ -92023,14 +93226,17 @@ var ts; var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; - var isValidAccess = allowTypeOrValue ? - // Any kind is allowed when dotting off namespace in internal import equals declaration - function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : - isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + var isValidAccess = isNamespaceName + // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. + ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + : allowTypeOrValue ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { - var symbol_2 = exportedSymbols_1[_i]; - if (isValidAccess(symbol_2)) { - symbols.push(symbol_2); + var exportedSymbol = exportedSymbols_1[_i]; + if (isValidAccess(exportedSymbol)) { + symbols.push(exportedSymbol); } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). @@ -92081,7 +93287,9 @@ var ts; var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { symbols.push(firstAccessibleSymbol); - symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = { type: "symbol-member" }; + var moduleSymbol = firstAccessibleSymbol.parent; + symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = + !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) ? { kind: 1 /* SymbolMemberNoExport */ } : { kind: 2 /* SymbolMemberExport */, moduleSymbol: moduleSymbol, isDefaultExport: false }; } } else { @@ -92171,7 +93379,7 @@ var ts; if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 0 /* ThisType */ }; symbols.push(symbol); } } @@ -92213,7 +93421,7 @@ var ts; } function filterGlobalCompletion(symbols) { var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); - var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile); + var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) keywordFilters = 5 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { @@ -92306,7 +93514,7 @@ var ts; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + var origin = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; if (detailsEntryId || stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; @@ -92372,7 +93580,8 @@ var ts; function isNewIdentifierDefinitionLocation(previousToken) { if (previousToken) { var containingNodeKind = previousToken.parent.kind; - switch (previousToken.kind) { + // Previous token may have been a keyword that was converted to an identifier. + switch (keywordForNode(previousToken)) { case 26 /* CommaToken */: return containingNodeKind === 189 /* CallExpression */ // func( a, | || containingNodeKind === 155 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ @@ -92409,13 +93618,6 @@ var ts; case 113 /* ProtectedKeyword */: return containingNodeKind === 152 /* PropertyDeclaration */; // class A{ public | } - // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: - return true; - } } return false; } @@ -92958,7 +94160,7 @@ var ts; case 3 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); case 4 /* FunctionLikeBodyKeywords */: - return !isClassMemberCompletionKeyword(kind); + return isFunctionLikeBodyKeyword(kind); case 5 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: @@ -92981,6 +94183,9 @@ var ts; return ts.isClassMemberModifier(kind); } } + function isFunctionLikeBodyKeyword(kind) { + return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } @@ -93027,7 +94232,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 303 /* SyntaxList */: + case 304 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -93135,7 +94340,7 @@ var ts; return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; if (!sourceFilesSet.has(fileName)) { - ts.Debug.assert(program.redirectTargetsSet.has(fileName)); + ts.Debug.assert(program.redirectTargetsMap.has(fileName)); var redirectTarget_1 = program.getSourceFile(fileName); var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; @@ -94447,7 +95652,8 @@ var ts; if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -94852,7 +96058,7 @@ var ts; - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. */ var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); - if (exposedByParent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } var scope; @@ -95485,7 +96691,8 @@ var ts; // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - var res_1 = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), fromRoot); + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); if (res_1) return res_1; // If the location is name of property symbol from object literal destructuring pattern @@ -95550,14 +96757,6 @@ var ts; return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); }); } - /** Gets all symbols for one property. Does not get symbols for every property. */ - function getPropertySymbolsFromContextualType(node, checker) { - var contextualType = checker.getContextualType(node.parent); - var name = ts.getNameFromPropertyName(node.name); - var symbol = contextualType && name && contextualType.getProperty(name); - return symbol ? [symbol] : - contextualType && contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; // TODO: GH#18217 - } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class @@ -95641,11 +96840,11 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName); - var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); @@ -95653,16 +96852,28 @@ var ts; } ts.getEditsForFileRename = getEditsForFileRename; // exported for tests - function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName) { + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return function (path) { - if (getCanonicalFileName(path) === canonicalOldPath) + var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) return newFileOrDirPath; - var suffix = ts.tryRemoveDirectoryPrefix(path, canonicalOldPath, getCanonicalFileName); + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; - }; + } } ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); + } function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; if (!configFile) @@ -95734,7 +96945,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { var allFiles = program.getSourceFiles(); - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -95756,17 +96967,17 @@ var ts; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. // TODO:GH#18217 - ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, program) + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences) + ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_14(sourceFile); + _loop_13(sourceFile); } } function combineNormal(pathA, pathB) { @@ -95786,14 +96997,14 @@ var ts; var resolved = host.resolveModuleNames ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); - return getSourceFileToImportFromResolved(resolved, oldToNew, program); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); } } - function getSourceFileToImportFromResolved(resolved, oldToNew, program) { - return resolved && ((resolved.resolvedModule && getIfInProgram(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfInProgram)); - function getIfInProgram(oldLocation) { + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); + function getIfExists(oldLocation) { var newLocation = oldToNew(oldLocation); - return program.getSourceFile(oldLocation) || newLocation !== undefined && program.getSourceFile(newLocation) + return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } : undefined; } @@ -95860,12 +97071,12 @@ var ts; // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || - // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias - symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + // TODO: GH#25533 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations && symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { return [sigInfo]; } else { - var defs = getDefinitionFromSymbol(typeChecker, symbol, node); + var defs = getDefinitionFromSymbol(typeChecker, symbol, node) || ts.emptyArray; // For a 'super()' call, put the signature first, else put the variable first. return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } @@ -95892,13 +97103,12 @@ var ts; // bar(({pr/*goto*/op1})=>{}); if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && (node === (parent.propertyName || parent.name))) { + var name_5 = ts.getNameFromPropertyName(node); var type = typeChecker.getTypeAtLocation(parent.parent); - if (type) { - var propSymbols = ts.getPropertySymbolsFromType(type, node); - if (propSymbols) { - return ts.flatMap(propSymbols, function (propSymbol) { return getDefinitionFromSymbol(typeChecker, propSymbol, node); }); - } - } + return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_5); + return prop && getDefinitionFromSymbol(typeChecker, prop, node); + }); } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. @@ -95910,10 +97120,13 @@ var ts; // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) var element = ts.getContainingObjectLiteralElement(node); - if (element && typeChecker.getContextualType(element.parent)) { - return ts.flatMap(ts.getPropertySymbolsFromContextualType(typeChecker, element), function (propertySymbol) { - return getDefinitionFromSymbol(typeChecker, propertySymbol, node); - }); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } } return getDefinitionFromSymbol(typeChecker, symbol, node); } @@ -95953,16 +97166,32 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); - if (!type) { + if (!symbol) return undefined; - } - if (type.isUnion() && !(type.flags & 32 /* Enum */)) { - return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); - } - return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); + var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); + var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); + // If a function returns 'void' or some other type with no definition, just return the function definition. + return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; + function definitionFromType(type, checker, node) { + return ts.flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], function (t) { + return t.symbol && getDefinitionFromSymbol(checker, t.symbol, node); + }); + } + function tryGetReturnTypeOfFunction(symbol, type, checker) { + // If the type is just a function's inferred type, + // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway. + if (type.symbol === symbol || + // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + symbol.valueDeclaration && type.symbol && ts.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { + var sigs = type.getCallSignatures(); + if (sigs.length === 1) + return checker.getReturnTypeOfSignature(ts.first(sigs)); + } + return undefined; + } function getDefinitionAndBoundSpan(program, sourceFile, position) { var definitions = getDefinitionAtPosition(program, sourceFile, position); if (!definitions || definitions.length === 0) { @@ -96037,7 +97266,7 @@ var ts; } } function getCallSignatureDefinition() { - return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + return ts.isCallOrNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) : undefined; } @@ -96111,48 +97340,83 @@ var ts; var JsDoc; (function (JsDoc) { var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", "augments", "author", - "argument", "borrows", "callback", "class", + "classdesc", "constant", "constructor", "constructs", + "copyright", "default", "deprecated", "description", + "emits", + "enum", "event", "example", + "exports", "extends", + "external", "field", - "fileOverview", + "file", + "fileoverview", + "fires", "function", + "generator", + "global", + "hideconstructor", + "host", "ignore", - "inheritDoc", + "implements", + "inheritdoc", "inner", + "instance", + "interface", + "kind", "lends", - "link", - "memberOf", + "license", + "listens", + "member", + "memberof", "method", + "mixes", + "module", "name", "namespace", + "override", + "package", "param", "private", - "prop", "property", + "protected", "public", + "readonly", "requires", "returns", "see", "since", "static", + "summary", "template", + "this", "throws", + "todo", + "tutorial", "type", "typedef", - "version" + "var", + "variation", + "version", + "virtual", + "yields" ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; @@ -96180,11 +97444,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: return [declaration]; case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -96207,14 +97471,14 @@ var ts; switch (tag.kind) { case 293 /* JSDocAugmentsTag */: return withNode(tag.class); - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: - case 302 /* JSDocPropertyTag */: - case 296 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -96340,13 +97604,15 @@ var ts; * be performed. */ function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { - // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); + if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { + // Non-empty comment already exists. return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var tokenStart = tokenAtPos.getStart(sourceFile); - if (!tokenAtPos || tokenStart < position) { + // Don't provide a doc comment template based on a *previous* node. (But an existing empty jsdoc comment will likely start before `position`.) + if (!existingDocComment && tokenStart < position) { return undefined; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); @@ -96395,45 +97661,48 @@ var ts; }).join(""); } function getCommentOwnerInfo(tokenAtPos) { - for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 237 /* FunctionDeclaration */: - case 194 /* FunctionExpression */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 153 /* MethodSignature */: - var parameters = commentOwner.parameters; - return { commentOwner: commentOwner, parameters: parameters }; - case 238 /* ClassDeclaration */: - case 239 /* InterfaceDeclaration */: - case 151 /* PropertySignature */: - case 241 /* EnumDeclaration */: - case 276 /* EnumMember */: - case 240 /* TypeAliasDeclaration */: - return { commentOwner: commentOwner }; - case 217 /* 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 277 /* SourceFile */: - return undefined; - case 242 /* 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 === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 202 /* 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.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + } + function getCommentOwnerInfoWorker(commentOwner) { + switch (commentOwner.kind) { + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 153 /* MethodSignature */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 273 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer); + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 151 /* PropertySignature */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 240 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; + case 217 /* 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 277 /* SourceFile */: + return "quit"; + case 242 /* 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 === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 202 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + return "quit"; } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; } } } @@ -96472,9 +97741,9 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_15 = function (sourceFile) { + var _loop_14 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { + if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; } sourceFile.getNamedDeclarations().forEach(function (declarations, name) { @@ -96484,7 +97753,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_15(sourceFile); + _loop_14(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -96527,45 +97796,28 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - if (name && ts.isPropertyNameLiteral(name)) { - containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); - return true; - } - else if (name && name.kind === 147 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; - } + return !!name && (pushLiteral(name, containers) || name.kind === 147 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // // [X.Y.Z]() { } - function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - if (ts.isPropertyNameLiteral(expression)) { - var text = ts.getTextOfIdentifierOrLiteral(expression); - if (includeLastPortion) { - containers.unshift(text); - } - return true; - } - if (ts.isPropertyAccessExpression(expression)) { - if (includeLastPortion) { - containers.unshift(expression.name.text); - } - return tryAddComputedPropertyName(expression.expression, containers, /*includeLastPortion*/ true); - } - return false; + function tryAddComputedPropertyName(expression, containers) { + return pushLiteral(expression, containers) + || ts.isPropertyAccessExpression(expression) && (containers.push(expression.name.text), true) && tryAddComputedPropertyName(expression.expression, containers); + } + function pushLiteral(node, containers) { + return ts.isPropertyNameLiteral(node) && (containers.push(ts.getTextOfIdentifierOrLiteral(node)), true); } 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 && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { + if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } + // Don't include the last portion. + containers.shift(); // Now, walk up our containers, adding all their names to the container array. var container = ts.getContainerNode(declaration); while (container) { @@ -96574,7 +97826,7 @@ var ts; } container = ts.getContainerNode(container); } - return containers; + return containers.reverse(); } function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. @@ -96713,7 +97965,7 @@ var ts; /** Call after calling `startNode` and adding children to it. */ function endNode() { if (parent.children) { - mergeChildren(parent.children); + mergeChildren(parent.children, parent); sortChildren(parent.children); } parent = parentsStack.pop(); @@ -96869,7 +98121,7 @@ var ts; } } /** Merge declarations of the same kind. */ - function mergeChildren(children) { + function mergeChildren(children, node) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var declName = ts.getNameOfDeclaration(child.node); @@ -96886,7 +98138,7 @@ var ts; if (itemsWithSameName instanceof Array) { for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { var itemWithSameName = itemsWithSameName_1[_i]; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } } @@ -96895,7 +98147,7 @@ var ts; } else { var itemWithSameName = itemsWithSameName; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } nameToItems.set(name, [itemWithSameName, child]); @@ -96903,16 +98155,16 @@ var ts; } }); } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { merge(a, b); return true; } return false; } /** a and b have the same name, but they may not be mergeable. */ - function shouldReallyMerge(a, b) { - if (a.kind !== b.kind) { + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { return false; } switch (a.kind) { @@ -96927,6 +98179,12 @@ var ts; return true; } } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { @@ -96943,7 +98201,7 @@ var ts; } target.children = ts.concatenate(target.children, source.children); if (target.children) { - mergeChildren(target.children); + mergeChildren(target.children, target); sortChildren(target.children); } } @@ -96965,7 +98223,7 @@ var ts; return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); - if (declName) { + if (declName && ts.isPropertyName(declName)) { return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { @@ -97042,7 +98300,7 @@ var ts; case 242 /* ModuleDeclaration */: case 277 /* SourceFile */: case 240 /* TypeAliasDeclaration */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return true; case 155 /* Constructor */: @@ -97143,7 +98401,7 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 242 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217 + return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { return !member.name || member.name.kind === 147 /* ComputedPropertyName */; @@ -97665,6 +98923,23 @@ var ts; return spanForObjectOrArrayLiteral(n); case 185 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); + case 258 /* JsxElement */: + return spanForJSXElement(n); + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 17 /* OpenBraceToken */; } @@ -97973,15 +99248,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_16 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_4 = _loop_16(start); - if (typeof state_4 === "object") - return state_4.value; + var state_3 = _loop_15(start); + if (typeof state_3 === "object") + return state_3.value; } return -1; } @@ -98523,7 +99798,7 @@ var ts; if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) return undefined; var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 147 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); @@ -98582,17 +99857,11 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - var ArgumentListKind; - (function (ArgumentListKind) { - ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; - ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; - ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; - ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind || (ArgumentListKind = {})); var InvocationKind; (function (InvocationKind) { InvocationKind[InvocationKind["Call"] = 0] = "Call"; InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + InvocationKind[InvocationKind["Contextual"] = 2] = "Contextual"; })(InvocationKind || (InvocationKind = {})); function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { var typeChecker = program.getTypeChecker(); @@ -98602,93 +99871,124 @@ var ts; // We are at the beginning of the file return undefined; } - if (shouldCarefullyCheckContext(triggerReason)) { - // In the middle of a string, don't provide signature help unless the user explicitly requested it. - if (ts.isInString(sourceFile, position, startingToken)) { - return undefined; - } + // Only need to be careful if the user typed a character and signature help wasn't showing. + var onlyUseSyntacticOwners = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { + return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); - // Semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - if (ts.isSourceFileJavaScript(sourceFile)) { - return createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken); - } - return undefined; + return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function shouldCarefullyCheckContext(reason) { - // Only need to be careful if the user typed a character and signature help wasn't showing. - return !!reason && reason.kind === "characterTyped"; - } - function getCandidateInfo(argumentInfo, checker) { - var invocation = argumentInfo.invocation; - if (invocation.kind === 0 /* Call */) { - var candidates = []; - var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = _a.invocation, argumentCount = _a.argumentCount; + switch (invocation.kind) { + case 0 /* Call */: { + if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { + return undefined; + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + } + case 1 /* TypeArgs */: { + if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + case 2 /* Contextual */: + return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + default: + return ts.Debug.assertNever(invocation); } - else { - var type = checker.getTypeAtLocation(invocation.called); // TODO: GH#18217 - var signatures = ts.isNewExpression(invocation.called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); - var candidates = signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= argumentInfo.argumentCount; }); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + function isSyntacticOwner(startingToken, node, sourceFile) { + if (!ts.isCallOrNewExpression(node)) + return false; + var invocationChildren = node.getChildren(sourceFile); + switch (startingToken.kind) { + case 19 /* OpenParenToken */: + return ts.contains(invocationChildren, startingToken); + case 26 /* CommaToken */: { + var containingList = ts.findContainingList(startingToken); + return !!containingList && ts.contains(invocationChildren, containingList); + } + case 27 /* LessThanToken */: + return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + default: + return false; } } function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + if (argumentInfo.invocation.kind === 2 /* Contextual */) + return undefined; // See if we can find some symbol with the call expression name that has call signatures. var expression = getExpressionFromInvocation(argumentInfo.invocation); - var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; - if (!name || !name.escapedText) { - return undefined; - } + var name = ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined; var typeChecker = program.getTypeChecker(); - var _loop_17 = function (sourceFile) { - var nameToDeclarations = sourceFile.getNamedDeclarations(); - var declarations = nameToDeclarations.get(name.text); - if (declarations) { - var _loop_18 = function (declaration) { - var symbol = declaration.symbol; - if (symbol) { - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); - if (type) { - var callSignatures_1 = type.getCallSignatures(); - if (callSignatures_1 && callSignatures_1.length) { - return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; - } - } - } - }; - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - var state_6 = _loop_18(declaration); - if (typeof state_6 === "object") - return state_6; + return name === undefined ? undefined : ts.firstDefined(program.getSourceFiles(), function (sourceFile) { + return ts.firstDefined(sourceFile.getNamedDeclarations().get(name), function (declaration) { + var type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration); + var callSignatures = type && type.getCallSignatures(); + if (callSignatures && callSignatures.length) { + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker); }); } - } - }; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - var state_5 = _loop_17(sourceFile); - if (typeof state_5 === "object") - return state_5.value; - } + }); + }); + } + function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(calledExpression, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); - return !info || info.kind === 0 /* TypeArguments */ || info.invocation.kind === 1 /* TypeArgs */ ? undefined + return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? undefined : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; } SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; + function getArgumentOrParameterListInfo(node, sourceFile) { + var info = getArgumentOrParameterListAndIndex(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex; + var argumentCount = getArgumentCount(list); + if (argumentIndex !== 0) { + ts.Debug.assertLessThan(argumentIndex, argumentCount); + } + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { list: list, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + } + function getArgumentOrParameterListAndIndex(node, sourceFile) { + if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. + return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; + } + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + var list = ts.findContainingList(node); + return list && { list: list, argumentIndex: getArgumentIndex(list, node) }; + } + } /** * Returns relevant information for the argument list and the current argument if we are * in the argument of an invocation; returns undefined otherwise. @@ -98697,8 +99997,6 @@ var ts; var parent = node.parent; if (ts.isCallOrNewExpression(parent)) { var invocation = parent; - var list = void 0; - var argumentIndex = void 0; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a signature help session // 2. The token is either not associated with a list, or ends a list, so the session should end @@ -98713,32 +100011,12 @@ var ts; // Case 3: // foo(a#, #b#) -> The token is buried inside a list, and should give signature help // Find out if 'node' is an argument, a type argument, or neither - if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { - // Find the list that starts right *after* the < or ( token. - // If the user has just opened a list, consider this item 0. - list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); - ts.Debug.assert(list !== undefined); - argumentIndex = 0; - } - else { - // findListItemInfo can return undefined if we are not in parent's argument list - // or type argument list. This includes cases where the cursor is: - // - To the right of the closing parenthesis, non-substitution template, or template tail. - // - Between the type arguments and the arguments (greater than token) - // - On the target of the call (parent.func) - // - On the 'new' keyword in a 'new' expression - list = ts.findContainingList(node); - if (!list) - return undefined; - argumentIndex = getArgumentIndex(list, node); - } - var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; - var argumentCount = getArgumentCount(list); - if (argumentIndex !== 0) { - ts.Debug.assertLessThan(argumentIndex, argumentCount); - } - var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var info = getArgumentOrParameterListInfo(node, sourceFile); + if (!info) + return undefined; + var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var isTypeParameterList = !!parent.typeArguments && parent.typeArguments.pos === list.pos; + return { isTypeParameterList: isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { // Check if we're actually inside the template; @@ -98746,6 +100024,7 @@ var ts; if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); } + return undefined; } else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { var templateExpression = parent; @@ -98774,7 +100053,7 @@ var ts; var attributeSpanStart = parent.attributes.pos; var attributeSpanEnd = ts.skipTrivia(sourceFile.text, parent.attributes.end, /*stopAfterLineBreak*/ false); return { - kind: 3 /* JSXAttributesArguments */, + isTypeParameterList: false, invocation: { kind: 0 /* Call */, node: parent }, argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart), argumentIndex: 0, @@ -98782,15 +100061,67 @@ var ts; }; } else { - var typeArgInfo = ts.isPossiblyTypeArgumentPosition(node, sourceFile); + var typeArgInfo = ts.getPossibleTypeArgumentsInfo(node, sourceFile); if (typeArgInfo) { var called = typeArgInfo.called, nTypeArguments = typeArgInfo.nTypeArguments; var invocation = { kind: 1 /* TypeArgs */, called: called }; var argumentsSpan = ts.createTextSpanFromBounds(called.getStart(sourceFile), node.end); - return { kind: 0 /* TypeArguments */, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; + return { isTypeParameterList: true, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; } + return undefined; } - return undefined; + } + function getImmediatelyContainingArgumentOrContextualParameterInfo(node, position, sourceFile, checker) { + return tryGetParameterInfo(node, position, sourceFile, checker) || getImmediatelyContainingArgumentInfo(node, position, sourceFile); + } + function getHighestBinary(b) { + return ts.isBinaryExpression(b.parent) ? getHighestBinary(b.parent) : b; + } + function countBinaryExpressionParameters(b) { + return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2; + } + function tryGetParameterInfo(startingToken, _position, sourceFile, checker) { + var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker); + if (!info) + return undefined; + var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var signatures = contextualType.getCallSignatures(); + if (signatures.length !== 1) + return undefined; + var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(contextualType.symbol) }; + return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { + if (startingToken.kind !== 19 /* OpenParenToken */ && startingToken.kind !== 26 /* CommaToken */) + return undefined; + var parent = startingToken.parent; + switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + case 154 /* MethodDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + var info = getArgumentOrParameterListInfo(startingToken, sourceFile); + if (!info) + return undefined; + var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; + var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); + return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; + case 202 /* BinaryExpression */: { + var highestBinary = getHighestBinary(parent); + var contextualType_1 = checker.getContextualType(highestBinary); + var argumentIndex_1 = startingToken.kind === 19 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; + var argumentCount_1 = countBinaryExpressionParameters(highestBinary); + return contextualType_1 && { contextualType: contextualType_1, argumentIndex: argumentIndex_1, argumentCount: argumentCount_1, argumentsSpan: ts.createTextSpanFromNode(parent) }; + } + default: + return undefined; + } + } + // The type of a function type node has a symbol at that node, but it's better to use the symbol for a parameter or type alias. + function chooseBetterSymbol(s) { + return s.name === "__type" /* Type */ + ? ts.firstDefined(s.declarations, function (d) { return ts.isFunctionTypeNode(d) ? d.parent.symbol : undefined; }) || s + : s; } function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may @@ -98867,7 +100198,7 @@ var ts; ts.Debug.assertLessThan(argumentIndex, argumentCount); } return { - kind: 2 /* TaggedTemplateArguments */, + isTypeParameterList: false, invocation: { kind: 0 /* Call */, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, @@ -98907,20 +100238,20 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile) { - var _loop_19 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker) { + var _loop_16 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); - var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); + var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker); if (argumentInfo) { return { value: argumentInfo }; } }; for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_7 = _loop_19(n); - if (typeof state_7 === "object") - return state_7.value; + var state_4 = _loop_16(n); + if (typeof state_4 === "object") + return state_4.value; } return undefined; } @@ -98934,101 +100265,194 @@ var ts; return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { - var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; - var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.called; - var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); - var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); - var printer = ts.createPrinter({ removeComments: true }); - var items = candidates.map(function (candidateSignature) { - var signatureHelpParameters; - var prefixDisplayParts = []; - var suffixDisplayParts = []; - if (callTargetDisplayParts) { - ts.addRange(prefixDisplayParts, callTargetDisplayParts); - } - var isVariadic; - if (isTypeParameterList) { - isVariadic = false; // type parameter lists are not variadic - prefixDisplayParts.push(ts.punctuationPart(27 /* LessThanToken */)); - 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) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); - }); - ts.addRange(suffixDisplayParts, parameterParts); - } - else { - isVariadic = candidateSignature.hasRestParameter; - var typeParameterParts = ts.mapToDisplayParts(function (writer) { - if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); - printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); - } - }); - ts.addRange(prefixDisplayParts, typeParameterParts); - prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - signatureHelpParameters = ts.map(candidateSignature.parameters, createSignatureHelpParameterForParameter); - suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); - } - var returnTypeParts = ts.mapToDisplayParts(function (writer) { - writer.writePunctuation(":"); - writer.writeSpace(" "); - var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); - if (predicate) { - typeChecker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); - } - else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); - } - }); - ts.addRange(suffixDisplayParts, returnTypeParts); - return { - isVariadic: isVariadic, - prefixDisplayParts: prefixDisplayParts, - suffixDisplayParts: suffixDisplayParts, - separatorDisplayParts: [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()], - parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment(typeChecker), - tags: candidateSignature.getJsDocTags() - }; - }); + function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { + var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); + var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; + var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var selectedItemIndex = candidates.indexOf(resolvedSignature); ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; - function createSignatureHelpParameterForParameter(parameter) { - var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); - printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); - }); - return { - name: parameter.name, - documentation: parameter.getDocumentationComment(typeChecker), - displayParts: displayParts, - isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) - }; + } + function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { + var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; + var prefixDisplayParts = callTargetDisplayParts.concat(prefix); + var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; + var documentation = candidateSignature.getDocumentationComment(checker); + var tags = candidateSignature.getJsDocTags(); + return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) { + return ts.mapToDisplayParts(function (writer) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = checker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); + } + else { + checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); + } + }); + } + function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; + var printer = ts.createPrinter({ removeComments: true }); + var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var parameterParts = ts.mapToDisplayParts(function (writer) { + var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); + }); + return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(27 /* LessThanToken */)], suffix: [ts.punctuationPart(29 /* GreaterThanToken */)].concat(parameterParts) }; + } + function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { + var isVariadic = candidateSignature.hasRestParameter; + var printer = ts.createPrinter({ removeComments: true }); + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); + } + }); + var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); + return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(19 /* OpenParenToken */)]), suffix: [ts.punctuationPart(20 /* CloseParenToken */)] }; + } + function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + } + function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { + var displayParts = ts.mapToDisplayParts(function (writer) { + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); + }); + return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + } + })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + var sourcemappedFileCache; + return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; } - function createSignatureHelpParameterForTypeParameter(typeParameter) { - var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); - }); - return { - name: typeParameter.symbol.name, - documentation: ts.emptyArray, - displayParts: displayParts, - isOptional: false - }; + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); + var comment = sourceMapCommentRegExp.exec(lineText); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!lineText.match(whitespaceOrMapCommentRegExp)) { + break; + } } } - })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + // swallow error + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + // obviously invalid map + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, getProgram(), sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function tryGetOriginalLocation(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); + return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + } + function tryGetGeneratedLocation(info) { + var program = getProgram(); + var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = ts.createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; })(ts || (ts = {})); /* @internal */ var ts; @@ -99036,6 +100460,7 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; + var checker = program.getDiagnosticsProducingTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { @@ -99066,8 +100491,8 @@ var ts; case 194 /* FunctionExpression */: var decl = ts.getDeclarationOfJSInitializer(node); if (decl) { - var symbol_3 = decl.symbol; - if (symbol_3 && (symbol_3.exports && symbol_3.exports.size || symbol_3.members && symbol_3.members.size)) { + var symbol_2 = decl.symbol; + if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); break; } @@ -99095,6 +100520,9 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } + if (ts.isFunctionLikeDeclaration(node)) { + addConvertToAsyncFunctionDiagnostics(node, checker, diags); + } node.forEachChild(check); } } @@ -99135,9 +100563,56 @@ var ts; return undefined; } } + function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { + var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; + if (ts.isAsyncFunction(node) || !node.body || !functionType) { + return; + } + var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); + var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { + return; + } + // collect all the return statements + // check that a property access expression exists in there and that it is a handler + var returnStatements = getReturnStatementsWithPromiseHandlers(node); + if (returnStatements.length > 0) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } + /** @internal */ + function getReturnStatementsWithPromiseHandlers(node) { + var returnStatements = []; + if (ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + else { + visit(node); + } + function visit(child) { + if (ts.isFunctionLike(child)) { + return; + } + if (ts.isReturnStatement(child)) { + ts.forEachChild(child, addHandlers); + } + function addHandlers(returnChild) { + if (isPromiseHandler(returnChild)) { + returnStatements.push(child); + } + } + ts.forEachChild(child, visit); + } + return returnStatements; + } + ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + function isPromiseHandler(node) { + return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && + (node.expression.name.text === "then" || node.expression.name.text === "catch")); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -99855,7 +101330,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_20 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -99874,7 +101349,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_20(opt); + _loop_17(opt); } return options; } @@ -101474,7 +102949,6 @@ var ts; function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); - var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { @@ -101503,17 +102977,20 @@ var ts; var child = nodes[i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } - if (listEndToken !== 0 /* Unknown */) { - if (formattingScanner.isOnToken()) { - var tokenInfo = formattingScanner.readTokenInfo(parent); - // consume the list end token only if it is still belong to the parent - // there might be the case when current token matches end token but does not considered as one - // function (x: function) <-- - // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { - // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); - } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.readTokenInfo(parent); + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } } } @@ -101689,7 +103166,6 @@ var ts; // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; - var parts; if (startLine === endLine) { if (!firstLineIsIndented) { // treat as single line comment @@ -101697,18 +103173,18 @@ var ts; } return; } - else { - parts = []; - var startPos = commentRange.pos; - for (var line = startLine; line < endLine; line++) { - var endOfLine = ts.getEndLinePosition(line, sourceFile); - parts.push({ pos: startPos, end: endOfLine }); - startPos = ts.getStartPositionOfLine(line + 1, sourceFile); - } - if (indentFinalLine) { - parts.push({ pos: startPos, end: commentRange.end }); - } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } + if (parts.length === 0) + return; var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); if (indentation === nonWhitespaceColumnInFirstPart.column) { @@ -102248,7 +103724,13 @@ var ts; getListIfStartEndIsInListRange(node.parent.parameters, start, end); } case 238 /* ClassDeclaration */: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 301 /* JSDocTemplateTag */: { + var typeParameters = node.parent.typeParameters; + return getListIfStartEndIsInListRange(typeParameters, node.getStart(sourceFile), end); + } case 190 /* NewExpression */: case 189 /* CallExpression */: { var start = node.getStart(sourceFile); @@ -102457,17 +103939,10 @@ var ts; function isControlFlowEndingStatement(kind, parent) { switch (kind) { case 228 /* ReturnStatement */: - case 232 /* ThrowStatement */: { - if (parent.kind !== 216 /* Block */) { - return true; - } - var grandParent = parent.parent; - // In a function, we may want to write inner functions after this. - return !(grandParent && grandParent.kind === 194 /* FunctionExpression */ || grandParent.kind === 237 /* FunctionDeclaration */); - } + case 232 /* ThrowStatement */: case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - return true; + return parent.kind !== 216 /* Block */; default: return false; } @@ -102627,7 +104102,7 @@ var ts; return this; }; ChangeTracker.prototype.delete = function (sourceFile, node) { - this.deletedNodes.push({ sourceFile: sourceFile, node: node, }); + this.deletedNodes.push({ sourceFile: sourceFile, node: node }); }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); @@ -103014,15 +104489,20 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_21 = function (sourceFile, node) { + var _loop_18 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { - deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + if (ts.isArray(node)) { + this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); + } + else { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } } }; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_21(sourceFile, node); + _loop_18(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -103072,14 +104552,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_22 = function (i) { + var _loop_19 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_22(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -103385,21 +104865,9 @@ var ts; case 235 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 148 /* TypeParameter */: { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node.parent); - if (typeParameters.length === 1) { - var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; - var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1); - var nextToken = ts.getTokenAtPosition(sourceFile, end); - ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); - ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); - changes.deleteNodeRange(sourceFile, previousToken, nextToken); - } - else { - deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); - } + case 148 /* TypeParameter */: + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - } case 251 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { @@ -103979,6 +105447,442 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "convertToAsyncFunction"; + var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, + }); + function convertToAsyncFunction(changes, sourceFile, position, checker, context) { + // get the function declaration - returns a promise + var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + if (!functionToConvert) { + return; + } + var synthNamesMap = ts.createMap(); + var originalTypeMap = ts.createMap(); + var allVarNames = []; + var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); + var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + var constIdentifiers = getConstIdentifiers(synthNamesMap); + var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + if (!returnStatements.length) { + return; + } + // add the async keyword + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + function startTransformation(node, nodeToReplace) { + var newNodes = transformExpression(node, transformer, node); + changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); + } + var _loop_20 = function (statement) { + if (ts.isCallExpression(statement)) { + startTransformation(statement, statement); + } + else { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + }; + for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { + var statement = returnStatements_1[_i]; + _loop_20(statement); + } + } + // Returns the identifiers that are never reassigned in the refactor + function getConstIdentifiers(synthNamesMap) { + var constIdentifiers = []; + synthNamesMap.forEach(function (val) { + if (val.numberOfAssignmentsOriginal === 0) { + constIdentifiers.push(val.identifier); + } + }); + return constIdentifiers; + } + /* + Finds all of the expressions of promise type that should not be saved in a variable during the refactor + */ + function getAllPromiseExpressionsToReturn(func, checker) { + if (!func.body) { + return ts.createMap(); + } + var setOfExpressionsToReturn = ts.createMap(); + ts.forEachChild(func.body, function visit(node) { + if (isPromiseReturningExpression(node, checker, "then")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + ts.forEach(node.arguments, visit); + } + else if (isPromiseReturningExpression(node, checker, "catch")) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned + ts.forEachChild(node, visit); + } + else if (isPromiseReturningExpression(node, checker)) { + setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); + // don't recurse here, since we won't refactor any children or arguments of the expression + } + else { + ts.forEachChild(node, visit); + } + }); + return setOfExpressionsToReturn; + } + /* + Returns true if node is a promise returning expression + If name is not undefined, node is a promise returning call of name + */ + function isPromiseReturningExpression(node, checker, name) { + var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); + var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); + return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); + } + function declaredInFile(symbol, sourceFile) { + return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile; + } + /* + Renaming of identifiers may be neccesary as the refactor changes scopes - + This function collects all existing identifier names and names of identifiers that will be created in the refactor. + It then checks for any collisions and renames them through getSynthesizedDeepClone + */ + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { + var identsToRenameMap = ts.createMap(); // key is the symbol id + ts.forEachChild(nodeToRename, function visit(node) { + if (!ts.isIdentifier(node)) { + ts.forEachChild(node, visit); + return; + } + var symbol = checker.getSymbolAtLocation(node); + var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile); + if (symbol && isDefinedInFile) { + var type = checker.getTypeAtLocation(node); + var lastCallSignature = getLastCallSignature(type, checker); + var symbolIdString = ts.getSymbolId(symbol).toString(); + // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) + // Note - the choice of the last call signature is arbitrary + if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { + var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + synthNamesMap.set(symbolIdString, synthName); + allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + } + // we only care about identifiers that are parameters and declarations (don't care about other uses) + else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + // if the identifier name conflicts with a different identifier that we've already seen + if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { + var newName = getNewNameIfConflict(node, allVarNames); + identsToRenameMap.set(symbolIdString, newName.identifier); + synthNamesMap.set(symbolIdString, newName); + allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + } + else { + var identifier = ts.getSynthesizedDeepClone(node); + identsToRenameMap.set(symbolIdString, identifier); + synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); + if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { + allVarNames.push({ identifier: identifier, symbol: symbol }); + } + } + } + } + }); + return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback); + function isExpressionOrCallOnTypePromise(child) { + var node = child.parent; + if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) { + var nodeType = checker.getTypeAtLocation(node); + var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType); + return !!isPromise; + } + return false; + } + function deepCloneCallback(node, clone) { + if (ts.isIdentifier(node)) { + var symbol = checker.getSymbolAtLocation(node); + var symboldIdString = symbol && ts.getSymbolId(symbol).toString(); + var renameInfo = symbol && synthNamesMap.get(symboldIdString); + if (renameInfo) { + var type = checker.getTypeAtLocation(node); + if (type) { + originalType.set(ts.getNodeId(clone).toString(), type); + } + } + } + var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); + if (val !== undefined) { + setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString()); + setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val); + } + } + } + function getNewNameIfConflict(name, allVarNames) { + var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + var numberOfAssignmentsOriginal = 0; + var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); + return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + // dispatch function to recursively build the refactoring + function transformExpression(node, transformer, outermostParent, prevArgName) { + if (!node) { + return []; + } + var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); + var nodeType = originalType || transformer.checker.getTypeAtLocation(node); + if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformThen(node, transformer, outermostParent, prevArgName); + } + else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformCatch(node, transformer, prevArgName); + } + else if (ts.isPropertyAccessExpression(node)) { + return transformExpression(node.expression, transformer, outermostParent, prevArgName); + } + else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + return transformPromiseCall(node, transformer, prevArgName); + } + return []; + } + function transformCatch(node, transformer, prevArgName) { + var func = node.arguments[0]; + var argName = getArgName(func, transformer); + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + /* + If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) + To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap + We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step + */ + if (prevArgName && !shouldReturn) { + prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block + transformer.synthNamesMap.forEach(function (val, key) { + if (val.identifier.text === prevArgName.identifier.text) { + transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + } + }); + // update the constIdentifiers list + if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { + transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + } + } + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); + var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); + var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); + /* + In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) + */ + var varDeclList; + if (prevArgName && !shouldReturn) { + var typeArray = prevArgName.types; + var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var varDecl = [ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), unionTypeNode)]; + varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); + } + var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); + return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; + } + function transformThen(node, transformer, outermostParent, prevArgName) { + var _a = node.arguments, res = _a[0], rej = _a[1]; + if (!res) { + return transformExpression(node.expression, transformer, outermostParent); + } + var argNameRes = getArgName(res, transformer); + var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); + if (rej) { + var argNameRej = getArgName(rej, transformer); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); + var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); + var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); + return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; + } + else { + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + } + return []; + } + function getFlagOfIdentifier(node, constIdentifiers) { + var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); + return inArr ? 2 /* Const */ : 1 /* Let */; + } + function transformPromiseCall(node, transformer, prevArgName) { + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); + // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call + var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; + var originalNodeParent = node.original ? node.original.parent : node.parent; + if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + } + else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return [ts.createStatement(ts.createAwait(node))]; + } + return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; + } + function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + } + return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + } + function getTransformationBody(func, prevArgName, argName, parent, transformer) { + var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; + var hasArgName = argName && argName.identifier.text.length > 0; + var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); + switch (func.kind) { + case 71 /* Identifier */: + if (!hasArgName) + break; + var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); + if (shouldReturn) { + return ts.createNodeArray([ts.createReturn(synthCall)]); + } + if (!hasPrevArgName) + break; + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); + var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); + var returnType = callSignatures && callSignatures[0].getReturnType(); + var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); + prevArgName.types.push(returnType); + return varDeclOrAssignment; + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + // Arrow functions with block bodies { } will enter this control flow + if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + var refactoredStmts = []; + for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { + refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + } + else { + refactoredStmts.push(statement); + } + } + return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : + removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + } + else { + var funcBody = func.body; + var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); + var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); + if (innerCbBody.length > 0) { + return ts.createNodeArray(innerCbBody); + } + if (hasPrevArgName && !shouldReturn) { + var type_3 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); + var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); + prevArgName.types.push(returnType_1); + return varDeclOrAssignment_1; + } + else { + return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + } + } + break; + } + return ts.createNodeArray([]); + } + function getLastCallSignature(type, checker) { + var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); + return callSignatures && callSignatures[callSignatures.length - 1]; + } + function removeReturns(stmts, prevArgName, constIdentifiers) { + var ret = []; + for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { + var stmt = stmts_1[_i]; + if (ts.isReturnStatement(stmt)) { + if (stmt.expression) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + } + } + else { + ret.push(ts.getSynthesizedDeepClone(stmt)); + } + } + return ts.createNodeArray(ret); + } + function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { + var innerCbBody = []; + for (var _i = 0, innerRetStmts_1 = innerRetStmts; _i < innerRetStmts_1.length; _i++) { + var stmt = innerRetStmts_1[_i]; + ts.forEachChild(stmt, function visit(node) { + if (ts.isCallExpression(node)) { + var temp = transformExpression(node, transformer, node, prevArgName); + innerCbBody = innerCbBody.concat(temp); + if (innerCbBody.length > 0) { + return; + } + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); + } + return innerCbBody; + } + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + function getArgName(funcNode, transformer) { + var numberOfAssignmentsOriginal = 0; + var types = []; + var name; + if (ts.isFunctionLikeDeclaration(funcNode)) { + if (funcNode.parameters.length > 0) { + var param = funcNode.parameters[0].name; + name = getMapEntryIfExists(param); + } + } + else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { + name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + else if (ts.isIdentifier(funcNode)) { + name = getMapEntryIfExists(funcNode); + } + if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { + return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + return name; + function getMapEntryIfExists(identifier) { + var originalNode = getOriginalNode(identifier); + var symbol = getSymbol(originalNode); + if (!symbol) { + return { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString()); + return mapEntry || { identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + } + function getSymbol(node) { + return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node); + } + function getOriginalNode(node) { + return node.original ? node.original : node; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -104522,6 +106426,8 @@ var ts; var errorCodes = [ ts.Diagnostics.Cannot_find_name_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics.Cannot_find_namespace_0.code, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, @@ -104542,6 +106448,7 @@ var ts; var sourceFile = context.sourceFile, preferences = context.preferences; // Namespace fixes don't conflict, so just build a list. var addToNamespace = []; + var importType = []; // Keys are import clause node IDs. var addToExisting = ts.createMap(); // Keys are module specifiers. @@ -104556,7 +106463,10 @@ var ts; case 0 /* UseNamespace */: addToNamespace.push(fix); break; - case 1 /* AddToExisting */: { + case 1 /* ImportType */: + importType.push(fix); + break; + case 2 /* AddToExisting */: { var importClause = fix.importClause, importKind = fix.importKind; var key = String(ts.getNodeId(importClause)); var entry = addToExisting.get(key); @@ -104572,7 +106482,7 @@ var ts; } break; } - case 2 /* AddNew */: { + case 3 /* AddNew */: { var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; var entry = newImports.get(moduleSpecifier); if (!entry) { @@ -104599,15 +106509,19 @@ var ts; } }); return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var quotePreference = ts.getQuotePreference(sourceFile, preferences); for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { var fix = addToNamespace_1[_i]; addNamespaceQualifier(changes, sourceFile, fix); } + for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { + var fix = importType_1[_a]; + addImportType(changes, sourceFile, fix, quotePreference); + } addToExisting.forEach(function (_a) { var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); }); - var quotePreference = ts.getQuotePreference(sourceFile, preferences); newImports.forEach(function (imports, moduleSpecifier) { addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); }); @@ -104618,8 +106532,9 @@ var ts; var ImportFixKind; (function (ImportFixKind) { ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; - ImportFixKind[ImportFixKind["AddToExisting"] = 1] = "AddToExisting"; - ImportFixKind[ImportFixKind["AddNew"] = 2] = "AddNew"; + ImportFixKind[ImportFixKind["ImportType"] = 1] = "ImportType"; + ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; })(ImportFixKind || (ImportFixKind = {})); var ImportKind; (function (ImportKind) { @@ -104628,12 +106543,12 @@ var ts; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, allSourceFiles, formatContext, symbolToken, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; - var fix = ts.first(getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences)); + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; } codefix.getImportCompletionAction = getImportCompletionAction; @@ -104648,22 +106563,25 @@ var ts; var exported = _a[_i]; if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ }); + result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); } } }); return result; } - function getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences) { + function isTypeOnlySymbol(s) { + return !(s.flags & 67216319 /* Value */); + } + function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); - var useNamespace = tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker); + var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports); // Don't bother providing an action to add a new import if we can add to an existing one. - var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences); + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences); return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); } - function tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker) { + function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { // It is possible that multiple import statements with the same specifier exist in the file. // e.g. // @@ -104676,13 +106594,13 @@ var ts; // 1. change "member3" to "ns.member3" // 2. add "member3" to the second import statement's import list // and it is up to the user to decide which one fits best. - return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; var namespace = getNamespaceImportName(declaration); if (namespace) { var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, symbolToken: symbolToken }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; } } }); @@ -104697,7 +106615,7 @@ var ts; return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) - ? { kind: 1 /* AddToExisting */, importClause: importClause, importKind: importKind } + ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind } : undefined; }); } @@ -104710,27 +106628,31 @@ var ts; return declaration.name; } } - function getExistingImportDeclarations(_a, checker, _b) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var imports = _b.imports; - return ts.mapDefined(imports, function (moduleSpecifier) { + function getExistingImportDeclarations(_a, checker, sourceFile) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + // Can't use an es6 import for a type in JS. + return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } - function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { + function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { + var isJs = ts.isSourceFileJavaScript(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ kind: 2 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); + return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. + return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; + }); }); }); // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); } - function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences) { + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, exportInfos, host, preferences); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); } function newImportInfoFromExistingSpecifier(_a) { var declaration = _a.declaration, importKind = _a.importKind; @@ -104739,13 +106661,13 @@ var ts; : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ ? declaration.moduleReference.expression : undefined; - return expression && ts.isStringLiteral(expression) ? { kind: 2 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; + return expression && ts.isStringLiteral(expression) ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; } function getFixesInfo(context, errorCode, pos) { var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) - : getFixesInfoForNonUMDImport(context, symbolToken); + : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken) : undefined; return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); } function getFixesInfoForUMDImport(_a, token) { @@ -104756,8 +106678,8 @@ var ts; return undefined; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; - var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()) }]; - var fixes = getFixForImport(exportInfos, symbolName, token, program, sourceFile, host, preferences); + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -104795,21 +106717,18 @@ var ts; } function getFixesInfoForNonUMDImport(_a, symbolToken) { var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; - // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. var checker = program.getTypeChecker(); // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken - && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) ? checker.getJsxNamespace() - : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; - if (!symbolName) - return undefined; + : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */); var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences); + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } @@ -104819,7 +106738,7 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); @@ -104840,7 +106759,6 @@ var ts; return originalSymbolToExportInfos; } function getDefaultExportInfo(defaultExport, moduleSymbol, program) { - var checker = program.getTypeChecker(); var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -104848,12 +106766,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = checker.getAliasedSymbol(defaultExport); - return getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); } else { - var moduleName = moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target); - return moduleName === undefined ? undefined : { symbolForMeaning: defaultExport, name: moduleName }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; } } function getNameForExportDefault(symbol) { @@ -104881,18 +106798,21 @@ var ts; case 0 /* UseNamespace */: addNamespaceQualifier(changes, sourceFile, fix); return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; - case 1 /* AddToExisting */: { + case 1 /* ImportType */: + addImportType(changes, sourceFile, fix, quotePreference); + return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; + case 2 /* AddToExisting */: { var importClause = fix.importClause, importKind = fix.importKind; doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); - return [ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; + return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! } - case 2 /* AddNew */: { + case 3 /* AddNew */: { var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); - return [ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: return ts.Debug.assertNever(fix); @@ -104925,8 +106845,16 @@ var ts; } } function addNamespaceQualifier(changes, sourceFile, _a) { - var namespacePrefix = _a.namespacePrefix, symbolToken = _a.symbolToken; - changes.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken)); + var namespacePrefix = _a.namespacePrefix, position = _a.position; + changes.insertText(sourceFile, position, namespacePrefix + "."); + } + function addImportType(changes, sourceFile, _a, quotePreference) { + var moduleSpecifier = _a.moduleSpecifier, position = _a.position; + changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); + } + function getImportTypePrefix(moduleSpecifier, quotePreference) { + var quote = ts.getQuoteFromPreference(quotePreference); + return "import(" + quote + moduleSpecifier + quote + ")."; } function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; @@ -105015,6 +106943,8 @@ var ts; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, ]; codefix.registerCodeFix({ @@ -105054,7 +106984,7 @@ var ts; var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { - suggestion = checker.getSuggestionForNonexistentModule(node, resolvedSourceFile.symbol); + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); } } else { @@ -105113,16 +107043,16 @@ var ts; var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); if (!info) return undefined; - if (info.kind === InfoKind.enum) { + if (info.kind === 0 /* Enum */) { var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; } - var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); - var addMember = inJs ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic)) : - getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, parentDeclaration, token, makeStatic); + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, fixIds: [fixId], @@ -105130,76 +107060,76 @@ var ts; var program = context.program, preferences = context.preferences; var checker = program.getTypeChecker(); var seen = ts.createMap(); - var classToMembers = new ts.NodeMap(); + var typeDeclToMembers = new ts.NodeMap(); return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { codefix.eachDiagnostic(context, errorCodes, function (diag) { var info = getInfo(diag.file, diag.start, checker); if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { return; } - if (info.kind === InfoKind.enum) { + if (info.kind === 0 /* Enum */) { var token = info.token, parentDeclaration = info.parentDeclaration; addEnumMemberDeclaration(changes, checker, token, parentDeclaration); } else { var parentDeclaration = info.parentDeclaration, token_2 = info.token; - var infos = classToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + var infos = typeDeclToMembers.getOrUpdate(parentDeclaration, function () { return []; }); if (!infos.some(function (i) { return i.token.text === token_2.text; })) infos.push(info); } }); - classToMembers.forEach(function (infos, classDeclaration) { - var superClasses = getAllSuperClasses(classDeclaration, checker); - var _loop_23 = function (info) { + typeDeclToMembers.forEach(function (infos, classDeclaration) { + var supers = getAllSupers(classDeclaration, checker); + var _loop_21 = function (info) { // If some superclass added this property, don't add it again. - if (superClasses.some(function (superClass) { - var superInfos = classToMembers.get(superClass); + if (supers.some(function (superClassOrInterface) { + var superInfos = typeDeclToMembers.get(superClassOrInterface); return !!superInfos && superInfos.some(function (_a) { var token = _a.token; return token.text === info.token.text; }); })) return "continue"; - var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; // Always prefer to add a method declaration if possible. if (call) { - addMethodDeclaration(context, changes, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); } else { - if (inJs) { - addMissingMemberInJs(changes, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic); + if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token.text, makeStatic); } else { var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); - addPropertyDeclaration(changes, classDeclarationSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic); } } }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_23(info); + _loop_21(info); } }); })); }, }); - function getAllSuperClasses(cls, checker) { + function getAllSupers(decl, checker) { var res = []; - while (cls) { - var superElement = ts.getClassExtendsHeritageElement(cls); + while (decl) { + var superElement = ts.getClassExtendsHeritageElement(decl); var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); if (superDecl) { res.push(superDecl); } - cls = superDecl; + decl = superDecl; } return res; } var InfoKind; (function (InfoKind) { - InfoKind[InfoKind["enum"] = 0] = "enum"; - InfoKind[InfoKind["class"] = 1] = "class"; + InfoKind[InfoKind["Enum"] = 0] = "Enum"; + InfoKind[InfoKind["ClassOrInterface"] = 1] = "ClassOrInterface"; })(InfoKind || (InfoKind = {})); function getInfo(tokenSourceFile, tokenPos, checker) { // The identifier of the missing property. eg: @@ -105216,33 +107146,34 @@ var ts; var symbol = leftExpressionType.symbol; if (!symbol || !symbol.declarations) return undefined; - var classDeclaration = ts.find(symbol.declarations, ts.isClassLike); - if (classDeclaration) { - var makeStatic = leftExpressionType.target !== checker.getDeclaredTypeOfSymbol(symbol); - var classDeclarationSourceFile = classDeclaration.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(classDeclarationSourceFile); + // Prefer to change the class instead of the interface if they are merged + var classOrInterface = ts.find(symbol.declarations, ts.isClassLike) || ts.find(symbol.declarations, ts.isInterfaceDeclaration); + if (classOrInterface) { + var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); + var declSourceFile = classOrInterface.getSourceFile(); + var inJs = ts.isSourceFileJavaScript(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); - return { kind: InfoKind.class, token: token, parentDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; + return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); if (enumDeclaration) { - return { kind: InfoKind.enum, token: token, parentDeclaration: enumDeclaration }; + return { kind: 0 /* Enum */, token: token, parentDeclaration: enumDeclaration }; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); + function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { if (classDeclaration.kind === 207 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); - changeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization); + changeTracker.insertNodeAfter(declSourceFile, classDeclaration, staticInitialization); } else { var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); @@ -105250,32 +107181,32 @@ var ts; return; } var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); - changeTracker.insertNodeAtConstructorEnd(classDeclarationSourceFile, classConstructor, propertyInitialization); + changeTracker.insertNodeAtConstructorEnd(declSourceFile, classConstructor, propertyInitialization); } } function initializePropertyToUndefined(obj, propertyName) { return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); } - function getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic) { + function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) { var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); - var addProp = createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, token.text, typeNode); - return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, token.text, typeNode)]; + var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)]; } function getTypeNode(checker, classDeclaration, token) { var typeNode; if (token.parent.parent.kind === 202 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); // TODO: GH#18217 + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); } - function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } - function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, @@ -105283,10 +107214,10 @@ var ts; /*initializer*/ undefined); var lastProp = getNodeToInsertPropertyAfter(classDeclaration); if (lastProp) { - changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + changeTracker.insertNodeAfter(declSourceFile, lastProp, property); } else { - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + changeTracker.insertNodeAtClassStart(declSourceFile, classDeclaration, property); } } // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. @@ -105300,7 +107231,7 @@ var ts; } return res; } - function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { + function createAddIndexSignatureAction(context, declSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. var stringTypeNode = ts.createKeywordTypeNode(137 /* StringKeyword */); var indexingParameter = ts.createParameter( @@ -105312,22 +107243,22 @@ var ts; var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(context, changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences); + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); - if (containingMethodDeclaration && containingMethodDeclaration.parent === classDeclaration) { - changeTracker.insertNodeAfter(classDeclarationSourceFile, containingMethodDeclaration, methodDeclaration); + if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { + changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); } else { - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); + changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); } } function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { @@ -105626,6 +107557,7 @@ var ts; var fixName = "unusedIdentifier"; var fixIdPrefix = "unusedIdentifier_prefix"; var fixIdDelete = "unusedIdentifier_delete"; + var fixIdInfer = "unusedIdentifier_infer"; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics._0_is_declared_but_never_used.code, @@ -105633,6 +107565,7 @@ var ts; ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, ts.Diagnostics.All_destructured_elements_are_unused.code, ts.Diagnostics.All_variables_are_unused.code, + ts.Diagnostics.All_type_parameters_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -105641,28 +107574,42 @@ var ts; var checker = program.getTypeChecker(); var sourceFiles = program.getSourceFiles(); var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (ts.isJSDocTemplateTag(token)) { + return [createDeleteFix(ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, token); }), ts.Diagnostics.Remove_template_tag)]; + } + if (token.kind === 27 /* LessThanToken */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return deleteTypeParameters(t, sourceFile, token); }); + return [createDeleteFix(changes, ts.Diagnostics.Remove_type_parameters)]; + } var importDecl = tryGetFullImport(token); if (importDecl) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); - return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)])]; } var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); }); if (delDestructure.length) { - return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(delDestructure, ts.Diagnostics.Remove_destructuring)]; } var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); if (delVar.length) { - return [codefix.createCodeFixAction(fixName, delVar, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + return [createDeleteFix(delVar, ts.Diagnostics.Remove_variable_statement)]; } var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { - return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); - }); - if (deletion.length) { - var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; - result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); + if (token.kind === 126 /* InferKeyword */) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return changeInferToUnknown(t, sourceFile, token); }); + var name = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name.text; + result.push(codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, ts.Diagnostics.Replace_all_unused_infer_with_unknown)); + } + else { + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); + if (deletion.length) { + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + } } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { @@ -105670,7 +107617,7 @@ var ts; } return result; }, - fixIds: [fixIdPrefix, fixIdDelete], + fixIds: [fixIdPrefix, fixIdDelete, fixIdInfer], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program; var checker = program.getTypeChecker(); @@ -105679,27 +107626,47 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, diag.start); switch (context.fixId) { case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); - } + tryPrefixDeclaration(changes, diag.code, sourceFile, token); break; case fixIdDelete: { + if (token.kind === 126 /* InferKeyword */) + break; // Can't delete var importDecl = tryGetFullImport(token); if (importDecl) { changes.delete(sourceFile, importDecl); } + else if (ts.isJSDocTemplateTag(token)) { + changes.delete(sourceFile, token); + } + else if (token.kind === 27 /* LessThanToken */) { + deleteTypeParameters(changes, sourceFile, token); + } else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && !tryDeleteFullVariableStatement(sourceFile, token, changes)) { tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); } break; } + case fixIdInfer: + if (token.kind === 126 /* InferKeyword */) { + changeInferToUnknown(changes, sourceFile, token); + } + break; default: ts.Debug.fail(JSON.stringify(context.fixId)); } }); }, }); + function changeInferToUnknown(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token.parent, ts.createKeywordTypeNode(142 /* UnknownKeyword */)); + } + function createDeleteFix(changes, diag) { + return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); + } + function deleteTypeParameters(changes, sourceFile, token) { + changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters)); + } // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(token) { return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; @@ -105726,13 +107693,19 @@ var ts; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { // Don't offer to prefix a property. - if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) { + if (errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) + return; + if (token.kind === 126 /* InferKeyword */) { + token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; + } + if (ts.isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); } } function canPrefix(token) { switch (token.parent.kind) { case 149 /* Parameter */: + case 148 /* TypeParameter */: return true; case 235 /* VariableDeclaration */: { var varDecl = token.parent; @@ -105823,69 +107796,54 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, }); - function doChange(changes, sourceFile, start) { + function doChange(changes, sourceFile, start, length) { var token = ts.getTokenAtPosition(sourceFile, start); var statement = ts.findAncestor(token, ts.isStatement); ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; - switch (container.kind) { - case 220 /* IfStatement */: - if (container.elseStatement) { - if (ts.isBlock(statement.parent)) { - changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements)); - } - else { - changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 220 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; } - break; - } - // falls through - case 222 /* WhileStatement */: - case 223 /* ForStatement */: - changes.delete(sourceFile, container); - break; - default: - if (ts.isBlock(statement.parent)) { - split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); }); - } - else { - changes.delete(sourceFile, statement); - } + // falls through + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } } - } - function shouldRemove(s) { - // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && - // `var x;` may declare a variable used above - !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); - } - function isPurelyTypeDeclaration(s) { - switch (s.kind) { - case 239 /* InterfaceDeclaration */: - case 240 /* TypeAliasDeclaration */: - return true; - case 242 /* ModuleDeclaration */: - return ts.getModuleInstanceState(s) !== 1 /* Instantiated */; - case 241 /* EnumDeclaration */: - return ts.hasModifier(s, 2048 /* Const */); - default: - return false; + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); } } - function sliceAfter(arr, value) { - var index = arr.indexOf(value); - ts.Debug.assert(index !== -1); - return arr.slice(index); - } - // Calls 'cb' with the start and end of each range where 'pred' is true. - function split(arr, pred, cb) { - ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); }); + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -106219,7 +108177,7 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences) { + function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { @@ -106244,7 +108202,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences)); + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -106760,7 +108718,7 @@ var ts; return; } else { - var indexType = checker.getTypeAtLocation(parent); + var indexType = checker.getTypeAtLocation(parent.argumentExpression); var indexUsageContext = {}; inferTypeFromContext(parent, checker, indexUsageContext); if (indexType.flags & 168 /* NumberLike */) { @@ -106818,10 +108776,10 @@ var ts; } } if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); // TODO: GH#18217 + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); } return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 } @@ -106941,7 +108899,7 @@ var ts; return getImportCodeFixesForExpression(context, node); } function getImportCodeFixesForExpression(context, expr) { - var type = context.program.getTypeChecker().getTypeAtLocation(expr); // TODO: GH#18217 + var type = context.program.getTypeChecker().getTypeAtLocation(expr); if (!(type.symbol && type.symbol.originatingImport)) { return []; } @@ -107523,7 +109481,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_24 = function (element) { + var _loop_22 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -107542,7 +109500,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_24(element); + _loop_22(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -108276,8 +110234,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), // TODO: GH#18217 - scope, 1 /* NoTruncation */); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -108582,7 +110539,7 @@ var ts; return scope.members; } else { - ts.assertTypeIsNever(scope); + ts.assertType(scope); } return ts.emptyArray; } @@ -108704,7 +110661,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { // TODO: GH#18217 + else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -108775,7 +110732,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_25 = function (i) { + var _loop_23 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -108815,7 +110772,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_25(i); + _loop_23(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -108837,7 +110794,7 @@ var ts; function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1 /* Read */; } if (inGenericContext) { - var type = checker.getTypeAtLocation(node); // TODO: GH#18217 + var type = checker.getTypeAtLocation(node); recordTypeParameterUsages(type); } if (ts.isDeclaration(node) && node.symbol) { @@ -109365,10 +111322,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_26 = function (sourceFile) { + var _loop_24 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_27 = function (statement) { + var _loop_25 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -109390,12 +111347,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_27(statement); + _loop_25(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_26(sourceFile); + _loop_24(sourceFile); } } function getNamespaceLikeImport(node) { @@ -109510,9 +111467,9 @@ var ts; if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { - var exports_3 = addExport(statement, useEs6Exports); - if (exports_3) - return exports_3; + var exports_2 = addExport(statement, useEs6Exports); + if (exports_2) + return exports_2; } return statement; }); @@ -109540,7 +111497,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -110071,7 +112028,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 302 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 303 /* LastJSDocNode */; }); return child.kind < 146 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -110141,7 +112098,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(303 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(304 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -110387,8 +112344,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -110871,7 +112828,6 @@ var ts; if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } - var sourcemappedFileCache; function log(message) { if (host.log) { host.log(message); @@ -110879,6 +112835,7 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -110976,7 +112933,7 @@ var ts; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during // the course of whatever called `synchronizeHostData` - sourcemappedFileCache = ts.createSourceFileLikeCache(host); + sourceMapper.clearCache(); // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); @@ -111125,31 +113082,15 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - // Try getting just type at this position and show - switch (node.kind) { - case 71 /* Identifier */: - if (ts.isLabelName(node)) { - // Type here will be 'any', avoid displaying this. - return undefined; - } - // falls through - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: - case 99 /* ThisKeyword */: - case 176 /* ThisType */: - case 97 /* SuperKeyword */: - // For the identifiers/this/super etc get the type at position - var type_4 = typeChecker.getTypeAtLocation(node); - return type_4 && { - kind: "" /* unknown */, - kindModifiers: "" /* none */, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined - }; - } - return undefined; + var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_4 && { + kind: "" /* unknown */, + kindModifiers: "" /* none */, + textSpan: ts.createTextSpanFromNode(node, sourceFile), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), + documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); @@ -111163,177 +113104,39 @@ var ts; tags: 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); - var property = type && checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); - if (property) { - return property; - } - } - return checker.getSymbolAtLocation(node); - } - function toLineColumnOffset(fileName, position) { - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var file = program.getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 - return file.getLineAndCharacterOfPosition(position); - } - // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) - var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/; - var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; - var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); - if (!mappedFile) { - return; - } - var starts = ts.getLineStarts(mappedFile); - for (var index = starts.length - 1; index >= 0; index--) { - var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); - var comment = sourceMapCommentRegExp.exec(lineText); - if (comment) { - return comment[1]; - } - // If we see a nonwhitespace/map comment-like line, break, to avoid scanning up the entire file - else if (!lineText.match(whitespaceOrMapCommentRegExp)) { - break; - } - } - } - function convertDocumentToSourceMapper(file, contents, mapFileName) { - var maps; - try { - maps = JSON.parse(contents); - } - catch (_a) { - // swallow error - } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { - // obviously invalid map - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - return file.sourceMapper = ts.sourcemaps.decode({ - readFile: function (s) { return host.readFile(s); }, - fileExists: function (s) { return host.fileExists(s); }, - getCanonicalFileName: getCanonicalFileName, - log: log, - }, mapFileName, maps, program, sourcemappedFileCache); - } - function getSourceMapper(fileName, file) { - if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - if (file.sourceMapper) { - return file.sourceMapper; - } - var mapFileName = scanForSourcemapURL(fileName); - if (mapFileName) { - var match = base64UrlRegExp.exec(mapFileName); - if (match) { - if (match[1]) { - var base64Object = match[1]; - return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); - } - // Not a data URL we can parse, skip it - mapFileName = undefined; - } - } - var possibleMapLocations = []; - if (mapFileName) { - possibleMapLocations.push(mapFileName); - } - possibleMapLocations.push(fileName + ".map"); - for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { - var location = possibleMapLocations_1[_i]; - var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); - if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 - } - } - return file.sourceMapper = ts.sourcemaps.identitySourceMapper; - } - function makeGetTargetOfMappedPosition(extract, create) { - return getTargetOfMappedPosition; - function getTargetOfMappedPosition(input, original) { - if (original === void 0) { original = input; } - var info = extract(input); - if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) { - var file = program.getSourceFile(info.fileName); - if (!file) { - var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName); - file = sourcemappedFileCache.get(path); - } - if (!file) { - return input; - } - var mapper = getSourceMapper(info.fileName, file); - var newLoc = mapper.getOriginalPosition(info); - if (newLoc === info) - return input; - return getTargetOfMappedPosition(create(newLoc, input, original), original); - } - return input; + function shouldGetType(sourceFile, node, position) { + switch (node.kind) { + case 71 /* Identifier */: + return !ts.isLabelName(node); + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: + // Don't return quickInfo if inside the comment in `a/**/.b` + return !ts.isInComment(sourceFile, position); + case 99 /* ThisKeyword */: + case 176 /* ThisType */: + case 97 /* SuperKeyword */: + return true; + default: + return false; } } - var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({ - containerKind: info.containerKind, - containerName: info.containerName, - fileName: newLoc.fileName, - kind: info.kind, - name: info.name, - textSpan: { - start: newLoc.position, - length: info.textSpan.length - }, - originalFileName: original.fileName, - originalTextSpan: original.textSpan - }); }); - function getTargetOfMappedDeclarationFiles(infos) { - return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); }); - } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position)); + return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } function getDefinitionAndBoundSpan(fileName, position) { synchronizeHostData(); - var result = ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); - if (!result) - return result; - var mappedDefs = getTargetOfMappedDeclarationFiles(result.definitions); - if (mappedDefs === result.definitions) { - return result; - } - return { - definitions: mappedDefs, - textSpan: result.textSpan - }; + return ts.GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); } function getTypeDefinitionAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedDeclarationFiles(ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position)); + return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } /// Goto implementation - var getTargetOfMappedImplementationLocation = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({ - fileName: newLoc.fileName, - kind: info.kind, - displayParts: info.displayParts, - textSpan: { - start: newLoc.position, - length: info.textSpan.length - }, - originalFileName: info.fileName, - originalTextSpan: info.textSpan - }); }); - function getTargetOfMappedImplementationLocations(infos) { - return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); }); - } function getImplementationAtPosition(fileName, position) { synchronizeHostData(); - return getTargetOfMappedImplementationLocations(ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position)); + return ts.FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { @@ -111346,7 +113149,8 @@ var ts; }); }); }); } function getDocumentHighlights(fileName, position, filesToSearch) { - ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === fileName; })); + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); var sourceFile = getValidSourceFile(fileName); @@ -111384,7 +113188,6 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } - /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); @@ -111584,7 +113387,7 @@ var ts; } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } - return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences); + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -111640,10 +113443,15 @@ var ts; return undefined; var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent : ts.isJsxText(token) ? token.parent : undefined; - if (element && !ts.tagNamesAreEquivalent(element.openingElement.tagName, element.closingElement.tagName)) { + if (element && isUnclosedTag(element)) { return { newText: "" }; } } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); @@ -111854,7 +113662,8 @@ var ts; getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, - toLineColumnOffset: toLineColumnOffset + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, }; } ts.createLanguageService = createLanguageService; @@ -111870,7 +113679,7 @@ var ts; function initializeNameTable(sourceFile) { var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteral(node) && literalIsName(node)) { + if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteralLike(node) && literalIsName(node)) { var text = ts.getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } @@ -111900,6 +113709,11 @@ var ts; */ /* @internal */ function getContainingObjectLiteralElement(node) { + var element = getContainingObjectLiteralElementWorker(node); + return element && (ts.isObjectLiteralExpression(element.parent) || ts.isJsxAttributes(element.parent)) ? element : undefined; + } + ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; + function getContainingObjectLiteralElementWorker(node) { switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -111914,37 +113728,40 @@ var ts; } return undefined; } - ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement; - /* @internal */ - function getPropertySymbolsFromContextualType(typeChecker, node) { - var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); // TODO: GH#18217 - return getPropertySymbolsFromType(contextualType, node.name); // TODO: GH#18217 + function getSymbolAtLocationForQuickInfo(node, checker) { + var object = getContainingObjectLiteralElement(node); + if (object) { + var contextualType = checker.getContextualType(object.parent); + var properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ false); + if (properties && properties.length === 1) { + return ts.first(properties); + } + } + return checker.getSymbolAtLocation(node); } - ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; + /** Gets all symbols for one property. Does not get symbols for every property. */ /* @internal */ - function getPropertySymbolsFromType(type, propName) { - var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); - if (name && type) { - var result_7 = []; - var symbol = type.getProperty(name); - if (type.flags & 262144 /* Union */) { - ts.forEach(type.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_7.push(symbol); - } - }); - return result_7; - } - if (symbol) { - result_7.push(symbol); - return result_7; - } + function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + if (!contextualType.isUnion()) { + var symbol = contextualType.getProperty(name); + return symbol ? [symbol] : ts.emptyArray; } - return undefined; + var discriminatedPropertySymbols = ts.mapDefined(contextualType.types, function (t) { return ts.isObjectLiteralExpression(node.parent) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name); }); + if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { + var symbol = contextualType.getProperty(name); + if (symbol) + return [symbol]; + } + if (discriminatedPropertySymbols.length === 0) { + // Bad discriminant -- do again without discriminating + return ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }); + } + return discriminatedPropertySymbols; } - ts.getPropertySymbolsFromType = getPropertySymbolsFromType; + ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; function isArgumentOfElementAccessExpression(node) { return node && node.parent && @@ -112712,7 +114529,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { var encoded = this.shimHost.getScriptFileNames(); - return this.files = JSON.parse(encoded); + return JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); @@ -113244,8 +115061,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) { - var ref = refs_2[_i]; + for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { + var ref = refs_1[_i]; result.push({ path: ts.normalizeSlashes(ref.fileName), position: ref.pos, @@ -113367,4 +115184,4 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = ts.versionMajorMinor; -//# sourceMappingURL=typescriptServices.js.map \ No newline at end of file +//# sourceMappingURL=typescriptServices.out.js.map \ No newline at end of file diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 3e74564a5566b..dd81fe55cedd6 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -86,7 +86,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.0"; + ts.versionMajorMinor = "3.1"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -1697,6 +1697,9 @@ var ts; if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { var candidateNameLowerCase = candidateName.toLowerCase(); if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } return candidate; } if (justCheckExactMatches) { @@ -1907,8 +1910,8 @@ var ts; return function (arg) { return f(arg) || g(arg); }; } ts.or = or; - function assertTypeIsNever(_) { } // tslint:disable-line no-empty - ts.assertTypeIsNever = assertTypeIsNever; + function assertType(_) { } // tslint:disable-line no-empty + ts.assertType = assertType; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -2370,23 +2373,24 @@ var ts; SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 296] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 297] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 298] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 299] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 300] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 301] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 302] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 296] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 297] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 298] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 299] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 300] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 301] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 302] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 303] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 303] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 304] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 304] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 305] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 306] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 307] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 308] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 305] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 306] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 307] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 308] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 309] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 309] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 310] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -2414,9 +2418,9 @@ var ts; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 302] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 303] = "LastJSDocNode"; SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 302] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 303] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -2744,6 +2748,7 @@ var ts; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; @@ -2777,8 +2782,6 @@ var ts; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasExports"] = 1955] = "HasExports"; - SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember"; @@ -2832,6 +2835,7 @@ var ts; InternalSymbolName["Resolving"] = "__resolving__"; InternalSymbolName["ExportEquals"] = "export="; InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); /* @internal */ var NodeCheckFlags; @@ -2888,7 +2892,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["UnionOfUnitTypes"] = 67108864] = "UnionOfUnitTypes"; + TypeFlags[TypeFlags["UnionOfPrimitiveTypes"] = 67108864] = "UnionOfPrimitiveTypes"; /* @internal */ TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ @@ -2931,7 +2935,7 @@ var ts; TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["NotUnit"] = 16749629] = "NotUnit"; + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 16748579] = "NotPrimitiveUnion"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ @@ -2965,6 +2969,7 @@ var ts; ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -3822,52 +3827,80 @@ var ts; */ /*@internal*/ function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); return createDirectoryWatcher; /** * Create the directory watcher for the dirPath. */ function createDirectoryWatcher(dirName, callback) { - var watcher = host.watchDirectory(dirName, function (fileName) { - // Call the actual callback - callback(fileName); - // Iterate through existing children and update the watches if needed - updateChildWatches(result, callback); - }); - var result = { - close: function () { - watcher.close(); - result.childWatches.forEach(ts.closeFileWatcher); - result = undefined; - }, + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { dirName: dirName, - childWatches: ts.emptyArray + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } }; - updateChildWatches(result, callback); - return result; } - function updateChildWatches(watcher, callback) { + function updateChildWatches(dirName, dirPath) { // Iterate through existing children and update the watches if needed - if (watcher) { - watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); } } /** * Watch the directories in the parentDir */ - function watchChildDirectories(parentDir, existingChildWatches, callback) { + function watchChildDirectories(parentDir, existingChildWatches) { var newChildWatches; ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch - return host.filePathComparer(childFullName, host.realpath(childFullName)) === 0 /* EqualTo */ ? childFullName : undefined; - }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); return newChildWatches || ts.emptyArray; /** * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName) { - var result = createDirectoryWatcher(childName, callback); + var result = createDirectoryWatcher(childName); addChildDirectoryWatcher(result); } /** @@ -3894,7 +3927,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; - // TODO: this is used as if it's certainly defined in many places. + // TODO: GH#18217 this is used as if it's certainly defined in many places. ts.sys = (function () { // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual // byte order mark from the specified encoding. Using any other byte order mark does @@ -4003,18 +4036,17 @@ var ts; process.stdout._handle.setBlocking(true); } }, - base64decode: Buffer.from ? function (input) { - return Buffer.from(input, "base64").toString("utf8"); - } : function (input) { - return new Buffer(input, "base64").toString("utf8"); - }, - base64encode: Buffer.from ? function (input) { - return Buffer.from(input).toString("base64"); - } : function (input) { - return new Buffer(input).toString("base64"); - } + bufferFrom: bufferFrom, + base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, + base64encode: function (input) { return bufferFrom(input).toString("base64"); }, }; return nodeSystem; + function bufferFrom(input, encoding) { + // See https://github.com/Microsoft/TypeScript/issues/25652 + return Buffer.from && Buffer.from !== Int8Array.from + ? Buffer.from(input, encoding) + : new Buffer(input, encoding); + } function isFileSystemCaseSensitive() { // win32\win64 are case insensitive platforms if (platform === "win32" || platform === "win64") { @@ -4067,7 +4099,7 @@ var ts; createWatchDirectoryUsing(dynamicPollingWatchFile || createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })) : watchDirectoryUsingFsWatch; var watchDirectoryRecursively = createRecursiveDirectoryWatcher({ - filePathComparer: ts.getStringComparer(!useCaseSensitiveFileNames), + useCaseSensitiveFileNames: useCaseSensitiveFileNames, directoryExists: directoryExists, getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; }, watchDirectory: watchDirectory, @@ -4077,8 +4109,7 @@ var ts; if (recursive) { return watchDirectoryRecursively(directoryName, callback); } - watchDirectory(directoryName, callback); - return undefined; // TODO: GH#18217 + return watchDirectory(directoryName, callback); }; } function createNonPollingWatchFile() { @@ -4761,6 +4792,8 @@ var ts; Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), + A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), + An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4813,7 +4846,7 @@ var ts; Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), - Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first: diag(2352, ts.DiagnosticCategory.Error, "Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352", "Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."), Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), @@ -5029,6 +5062,9 @@ var ts; Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), + Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), + Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), 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."), @@ -5115,8 +5151,11 @@ var ts; Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), - _0_was_declared_here: diag(2728, ts.DiagnosticCategory.Error, "_0_was_declared_here_2728", "'{0}' was declared here."), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), + An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), + Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), + Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), 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}'."), @@ -5230,6 +5269,7 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5420,6 +5460,7 @@ var ts; Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5479,12 +5520,14 @@ var ts; Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), - Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Error, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{0}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5514,6 +5557,7 @@ var ts; Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), 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."), @@ -5544,6 +5588,7 @@ var ts; Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), + This_may_be_converted_to_an_async_function: diag(80006, ts.DiagnosticCategory.Suggestion, "This_may_be_converted_to_an_async_function_80006", "This may be converted to an async function."), Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), @@ -5554,6 +5599,8 @@ var ts; Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), + Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), + Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5571,6 +5618,10 @@ var ts; Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), + Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), + Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), + Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), + Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), 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_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -5633,6 +5684,8 @@ var ts; Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), + Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), + Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), }; })(ts || (ts = {})); var ts; @@ -7386,6 +7439,7 @@ var ts; } function scanJSDocToken() { startPos = tokenPos = pos; + tokenFlags = 0; if (pos >= end) { return token = 1 /* EndOfFileToken */; } @@ -7404,6 +7458,7 @@ var ts; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: + tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: return token = 39 /* AsteriskToken */; @@ -7538,6 +7593,7 @@ var ts; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -7646,6 +7702,19 @@ var ts; return undefined; } ts.findAncestor = findAncestor; + function forEachAncestor(node, callback) { + while (true) { + var res = callback(node); + if (res === "quit") + return undefined; + if (res !== undefined) + return res; + if (ts.isSourceFile(node)) + return undefined; + node = node.parent; + } + } + ts.forEachAncestor = forEachAncestor; function forEachEntry(map, callback) { var _a; var iterator = map.entries(); @@ -7869,26 +7938,22 @@ var ts; } ts.nodeIsPresent = nodeIsPresent; /** - * Appends a range of value to begin of an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. + * Prepends statements to an array while taking care of prologue directives. */ - function prependStatements(to, from) { + function addStatementsAfterPrologue(to, from) { if (from === undefined || from.length === 0) return to; - if (to === undefined) - return from.slice(); - var prologue = to.length && isPrologueDirective(to[0]) && to.shift(); - to.unshift.apply(to, from); - if (prologue) { - to.unshift(prologue); + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } } + to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.prependStatements = prependStatements; + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; /** * Determine if the given comment is a triple-slash * @@ -7931,7 +7996,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 303 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 304 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8019,11 +8084,6 @@ var ts; return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; - // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' - function escapeLeadingUnderscores(identifier) { - return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); - } - ts.escapeLeadingUnderscores = escapeLeadingUnderscores; // Make an identifier from an external module name by extracting the string after the last "/" and replacing // all non-alphanumeric characters with underscores function makeIdentifierFromModuleName(moduleName) { @@ -8098,6 +8158,10 @@ var ts; return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; + function getNonAugmentationDeclaration(symbol) { + return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + } + ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator); } @@ -8128,6 +8192,18 @@ var ts; } ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 291 /* JSDocSignature */: + return true; + default: + ts.assertType(node); + return isDeclarationWithTypeParameterChildren(node); + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { case 158 /* CallSignature */: case 159 /* ConstructSignature */: @@ -8140,7 +8216,7 @@ var ts; case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: case 240 /* TypeAliasDeclaration */: - case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTemplateTag */: case 237 /* FunctionDeclaration */: case 154 /* MethodDeclaration */: case 155 /* Constructor */: @@ -8148,16 +8224,13 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: - case 291 /* JSDocSignature */: return true; default: - ts.assertTypeIsNever(node); + ts.assertType(node); return false; } } - ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { case 247 /* ImportDeclaration */: @@ -8212,11 +8285,11 @@ var ts; return name.escapedText; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return escapeLeadingUnderscores(name.text); + return ts.escapeLeadingUnderscores(name.text); case 147 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! + return isStringOrNumericLiteralLike(name.expression) ? ts.escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } ts.getTextOfPropertyName = getTextOfPropertyName; @@ -8365,9 +8438,7 @@ var ts; } ts.isImportCall = isImportCall; function isLiteralImportTypeNode(n) { - return n.kind === 181 /* ImportType */ && - n.argument.kind === 180 /* LiteralType */ && - ts.isStringLiteral(n.argument.literal); + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { @@ -8456,6 +8527,8 @@ var ts; return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case 148 /* TypeParameter */: return node === parent.constraint; + case 301 /* JSDocTemplateTag */: + return node === parent.constraint; case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: case 149 /* Parameter */: @@ -9055,6 +9128,8 @@ var ts; return true; case 209 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 274 /* ShorthandPropertyAssignment */: + return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); } @@ -9125,12 +9200,15 @@ var ts; } ts.isStringDoubleQuoted = isStringDoubleQuoted; function getDeclarationOfJSInitializer(node) { - if (!isInJavaScriptFile(node) || !node.parent) { + if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + return undefined; + } name = node.parent.name; decl = node.parent; } @@ -9288,8 +9366,12 @@ var ts; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder function getSpecialPropertyAssignmentKind(expr) { - if (!isInJavaScriptFile(expr) || - expr.operatorToken.kind !== 58 /* EqualsToken */ || + var special = getSpecialPropertyAssignmentKindWorker(expr); + return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getSpecialPropertyAssignmentKindWorker(expr) { + if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; } @@ -9300,7 +9382,6 @@ var ts; } return getSpecialPropertyAccessKind(lhs); } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getSpecialPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; @@ -9348,6 +9429,14 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function isFunctionSymbol(symbol) { + if (!symbol || !symbol.valueDeclaration) { + return false; + } + var decl = symbol.valueDeclaration; + return decl.kind === 237 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + } + ts.isFunctionSymbol = isFunctionSymbol; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); } @@ -9424,7 +9513,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 301 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + return node.kind === 302 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -9712,7 +9801,10 @@ var ts; } else { var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + return ts.isBinaryExpression(binExp) && + getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + (binExp.left.symbol || binExp.symbol) && + ts.getNameOfDeclaration(binExp) === name; } } default: @@ -9915,12 +10007,10 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isStringOrNumericLiteral(node) { - var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 8 /* NumericLiteral */; + function isStringOrNumericLiteralLike(node) { + return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); } - ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike; /** * A declaration has a dynamic name if both of the following are true: * 1. The declaration has a computed property name @@ -9935,7 +10025,7 @@ var ts; ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { return name.kind === 147 /* ComputedPropertyName */ && - !isStringOrNumericLiteral(name.expression) && + !isStringOrNumericLiteralLike(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } ts.isDynamicName = isDynamicName; @@ -9949,22 +10039,24 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 /* Identifier */) { - return name.escapedText; - } - if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(name.text); - } - if (name.kind === 147 /* ComputedPropertyName */) { - var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { - return escapeLeadingUnderscores(nameExpression.text); - } + switch (name.kind) { + case 71 /* Identifier */: + return name.escapedText; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return ts.escapeLeadingUnderscores(name.text); + case 147 /* ComputedPropertyName */: + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + else if (isStringOrNumericLiteralLike(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + return undefined; + default: + return ts.Debug.assertNever(name); } - return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; function isPropertyNameLiteral(node) { @@ -9984,7 +10076,7 @@ var ts; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return node.kind === 71 /* Identifier */ ? node.escapedText : escapeLeadingUnderscores(node.text); + return node.kind === 71 /* Identifier */ ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { @@ -10105,7 +10197,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return 0; case 206 /* SpreadElement */: return 1; @@ -10483,27 +10575,30 @@ var ts; return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; - function getOwnEmitOutputFilePath(sourceFile, host, extension) { + function getOwnEmitOutputFilePath(fileName, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; if (compilerOptions.outDir) { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); } else { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); } return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; - function getDeclarationEmitOutputFilePath(sourceFile, host) { - var options = host.getCompilerOptions(); + function getDeclarationEmitOutputFilePath(fileName, host) { + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } - ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; /** * Gets the source files that are expected to have an emit output. * @@ -10535,14 +10630,17 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - var commonSourceDirectory = host.getCommonSourceDirectory(); - var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } - ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); @@ -10615,7 +10713,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 156 /* GetAccessor */ || member.kind === 157 /* SetAccessor */) + if (ts.isAccessor(member) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -10649,7 +10747,10 @@ var ts; * parsed in a JavaScript file, gets the type annotation from JSDoc. */ function getEffectiveTypeAnnotationNode(node) { - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); + var type = node.type; + if (type || !isInJavaScriptFile(node)) + return type; + return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; function getTypeAnnotationNode(node) { @@ -10661,27 +10762,11 @@ var ts; * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { - if (ts.isJSDocSignature(node)) { - return node.type && node.type.typeExpression && node.type.typeExpression.type; - } - return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + return ts.isJSDocSignature(node) ? + node.type && node.type.typeExpression && node.type.typeExpression.type : + node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - /** - * Gets the effective type parameters. If the node was parsed in a - * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. - */ - function getEffectiveTypeParameterDeclarations(node) { - if (ts.isJSDocSignature(node)) { - return ts.emptyArray; - } - if (isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); - return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); - } - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray); - } - ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); } @@ -11448,7 +11533,9 @@ var ts; return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; case 202 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; - return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; + return left === node && isAssignmentOperator(operatorToken.kind) ? + operatorToken.kind === 58 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() + : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); default: @@ -11978,6 +12065,11 @@ var ts; return undefined; } ts.getParseTreeNode = getParseTreeNode; + /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; /** * Remove extra underscore from escaped identifier text content. * @@ -12063,8 +12155,8 @@ var ts; switch (declaration.kind) { case 71 /* Identifier */: return declaration; - case 302 /* JSDocPropertyTag */: - case 296 /* JSDocParameterTag */: { + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: { var name = declaration.name; if (name.kind === 146 /* QualifiedName */) { return name.right; @@ -12083,7 +12175,7 @@ var ts; return undefined; } } - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); case 252 /* ExportAssignment */: { var expression = declaration.expression; @@ -12168,6 +12260,11 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc enum tag for the node if present */ + function getJSDocEnumTag(node) { + return getFirstJSDocTag(node, ts.isJSDocEnumTag); + } + ts.getJSDocEnumTag = getJSDocEnumTag; /** Gets the JSDoc this tag for the node if present */ function getJSDocThisTag(node) { return getFirstJSDocTag(node, ts.isJSDocThisTag); @@ -12213,14 +12310,27 @@ var ts; } ts.getJSDocType = getJSDocType; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node) { var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } } ts.getJSDocReturnType = getJSDocReturnType; /** Get all JSDoc tags related to a node, including those on parent nodes. */ @@ -12244,6 +12354,28 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveConstraintOfTypeParameter(node) { + return node.constraint ? node.constraint + : ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; + } + ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -12481,7 +12613,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 305 /* PartiallyEmittedExpression */) { + while (node.kind === 306 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -12884,36 +13016,40 @@ var ts; return node.kind === 294 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocEnumTag(node) { + return node.kind === 296 /* JSDocEnumTag */; + } + ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 298 /* JSDocThisTag */; + return node.kind === 299 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 296 /* JSDocParameterTag */; + return node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 297 /* JSDocReturnTag */; + return node.kind === 298 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 299 /* JSDocTypeTag */; + return node.kind === 300 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 300 /* JSDocTemplateTag */; + return node.kind === 301 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 301 /* JSDocTypedefTag */; + return node.kind === 302 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 302 /* JSDocPropertyTag */; + return node.kind === 303 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 302 /* JSDocPropertyTag */ || node.kind === 296 /* JSDocParameterTag */; + return node.kind === 303 /* JSDocPropertyTag */ || node.kind === 297 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { @@ -12936,7 +13072,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 303 /* SyntaxList */; + return n.kind === 304 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -13401,8 +13537,8 @@ var ts; case 206 /* SpreadElement */: case 210 /* AsExpression */: case 208 /* OmittedExpression */: - case 306 /* CommaListExpression */: - case 305 /* PartiallyEmittedExpression */: + case 307 /* CommaListExpression */: + case 306 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13416,12 +13552,12 @@ var ts; ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 305 /* PartiallyEmittedExpression */; + return node.kind === 306 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 304 /* NotEmittedStatement */; + return node.kind === 305 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13532,9 +13668,9 @@ var ts; || kind === 240 /* TypeAliasDeclaration */ || kind === 148 /* TypeParameter */ || kind === 235 /* VariableDeclaration */ - || kind === 301 /* JSDocTypedefTag */ + || kind === 302 /* JSDocTypedefTag */ || kind === 295 /* JSDocCallbackTag */ - || kind === 302 /* JSDocPropertyTag */; + || kind === 303 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { return kind === 237 /* FunctionDeclaration */ @@ -13569,14 +13705,14 @@ var ts; || kind === 217 /* VariableStatement */ || kind === 222 /* WhileStatement */ || kind === 229 /* WithStatement */ - || kind === 304 /* NotEmittedStatement */ - || kind === 308 /* EndOfDeclarationMarker */ - || kind === 307 /* MergeDeclarationMarker */; + || kind === 305 /* NotEmittedStatement */ + || kind === 309 /* EndOfDeclarationMarker */ + || kind === 308 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 300 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -13671,7 +13807,7 @@ var ts; /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 302 /* LastJSDocNode */; + return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 303 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ @@ -13682,7 +13818,7 @@ var ts; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 302 /* LastJSDocTagNode */; + return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 303 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -13707,45 +13843,6 @@ var ts; return !!node.type; } ts.hasType = hasType; - /* True if the node could have a type node a `.type` */ - /* @internal */ - function couldHaveType(node) { - switch (node.kind) { - case 149 /* Parameter */: - case 151 /* PropertySignature */: - case 152 /* PropertyDeclaration */: - case 153 /* MethodSignature */: - case 154 /* MethodDeclaration */: - case 155 /* Constructor */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - case 158 /* CallSignature */: - case 159 /* ConstructSignature */: - case 160 /* IndexSignature */: - case 161 /* TypePredicate */: - case 163 /* FunctionType */: - case 164 /* ConstructorType */: - case 175 /* ParenthesizedType */: - case 177 /* TypeOperator */: - case 179 /* MappedType */: - case 192 /* TypeAssertionExpression */: - case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: - case 210 /* AsExpression */: - case 235 /* VariableDeclaration */: - case 237 /* FunctionDeclaration */: - case 240 /* TypeAliasDeclaration */: - case 281 /* JSDocTypeExpression */: - case 284 /* JSDocNullableType */: - case 285 /* JSDocNonNullableType */: - case 286 /* JSDocOptionalType */: - case 287 /* JSDocFunctionType */: - case 288 /* JSDocVariadicType */: - return true; - } - return false; - } - ts.couldHaveType = couldHaveType; /** True if has initializer node attached to it. */ /* @internal */ function hasInitializer(node) { @@ -13759,18 +13856,7 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - switch (node.kind) { - case 265 /* JsxAttribute */: - case 267 /* JsxSpreadAttribute */: - case 273 /* PropertyAssignment */: - case 274 /* ShorthandPropertyAssignment */: - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - return true; - default: - return false; - } + return node.kind === 265 /* JsxAttribute */ || node.kind === 267 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ @@ -14028,7 +14114,7 @@ var ts; } ts.unusedLabelIsError = unusedLabelIsError; function getAreDeclarationMapsEnabled(options) { - return !!(options.declaration && options.declarationMap); + return !!(getEmitDeclarations(options) && options.declarationMap); } ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; function getAllowSyntheticDefaultImports(compilerOptions) { @@ -14048,6 +14134,14 @@ var ts; return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } ts.getStrictOptionValue = getStrictOptionValue; + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { + if (oldOptions === newOptions) { + return false; + } + return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || + (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + } + ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14212,6 +14306,12 @@ var ts; return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); } ts.getDirectoryPath = getDirectoryPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; function isUrl(path) { return getEncodedRootLength(path) < 0; } @@ -15064,6 +15164,100 @@ var ts; return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); } ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.tryAdd = function (node) { + if (this.has(node)) + return false; + this.add(node); + return true; + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + function rangeOfNode(node) { + return { pos: ts.getTokenPosOfNode(node), end: node.end }; + } + ts.rangeOfNode = rangeOfNode; + function rangeOfTypeParameters(typeParameters) { + // Include the `<>` + return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 }; + } + ts.rangeOfTypeParameters = rangeOfTypeParameters; + function skipTypeChecking(sourceFile, options) { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; + } + ts.skipTypeChecking = skipTypeChecking; })(ts || (ts = {})); var ts; (function (ts) { @@ -15481,7 +15675,7 @@ var ts; return visitNode(cbNode, node.expression); case 256 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 258 /* JsxElement */: return visitNode(cbNode, node.openingElement) || @@ -15521,8 +15715,8 @@ var ts; visitNode(cbNode, node.type); case 289 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 296 /* JSDocParameterTag */: - case 302 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + case 303 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15531,15 +15725,15 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 297 /* JSDocReturnTag */: + case 298 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 299 /* JSDocTypeTag */: + case 300 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); case 293 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 300 /* JSDocTemplateTag */: - return visitNodes(cbNode, cbNodes, node.typeParameters); - case 301 /* JSDocTypedefTag */: + case 301 /* JSDocTemplateTag */: + return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); + case 302 /* JSDocTypedefTag */: if (node.typeExpression && node.typeExpression.kind === 281 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || @@ -15552,13 +15746,15 @@ var ts; case 295 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 298 /* JSDocThisTag */: + case 299 /* JSDocThisTag */: + return visitNode(cbNode, node.typeExpression); + case 296 /* JSDocEnumTag */: return visitNode(cbNode, node.typeExpression); case 291 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNodes(cbNode, cbNodes, node.parameters) || + ts.forEach(node.typeParameters, cbNode) || + ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); case 290 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { @@ -15568,7 +15764,7 @@ var ts; } } return; - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -16417,7 +16613,7 @@ var ts; return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); @@ -16440,7 +16636,7 @@ var ts; return isIdentifierOrPattern(); case 10 /* ArrayBindingElements */: return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: return isIdentifier(); case 15 /* ArrayLiteralMembers */: if (token() === 26 /* CommaToken */) { @@ -16450,13 +16646,15 @@ var ts; case 11 /* ArgumentExpressions */: return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: - return isStartOfParameter(); - case 19 /* TypeArguments */: - case 20 /* TupleElementTypes */: + return isStartOfParameter(/*isJSDocParameter*/ false); + case 17 /* JSDocParameters */: + return isStartOfParameter(/*isJSDocParameter*/ true); + case 20 /* TypeArguments */: + case 21 /* TupleElementTypes */: return token() === 26 /* CommaToken */ || isStartOfType(); - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return isHeritageClause(); - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return ts.tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; @@ -16521,7 +16719,7 @@ var ts; case 6 /* EnumMembers */: case 12 /* ObjectLiteralMembers */: case 9 /* ObjectBindingElements */: - case 22 /* ImportOrExportSpecifiers */: + case 23 /* ImportOrExportSpecifiers */: return token() === 18 /* CloseBraceToken */; case 3 /* SwitchClauseStatements */: return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; @@ -16529,24 +16727,25 @@ var ts; return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // Tokens other than '>' are here for better error recovery return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; case 15 /* ArrayLiteralMembers */: - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: case 10 /* ArrayBindingElements */: return token() === 22 /* CloseBracketToken */; + case 17 /* JSDocParameters */: case 16 /* Parameters */: - case 17 /* RestProperties */: + case 18 /* RestProperties */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // All other tokens should cause the type-argument to terminate except comma token return token() !== 26 /* CommaToken */; - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; case 13 /* JsxAttributes */: return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; @@ -16579,7 +16778,7 @@ var ts; } // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 23 /* Count */; kind++) { + for (var kind = 0; kind < 24 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; @@ -16691,24 +16890,25 @@ var ts; return isReusableTypeMember(node); case 8 /* VariableDeclarations */: return isReusableVariableDeclaration(node); + case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 17 /* RestProperties */: + case 18 /* RestProperties */: return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 21 /* HeritageClauses */: + case 22 /* HeritageClauses */: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 18 /* TypeParameters */: + case 19 /* TypeParameters */: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 20 /* TupleElementTypes */: + case 21 /* TupleElementTypes */: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -16716,7 +16916,7 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 19 /* TypeArguments */: + case 20 /* TypeArguments */: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. @@ -16866,7 +17066,7 @@ var ts; case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected; case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; - case 17 /* RestProperties */: // fallthrough + case 18 /* RestProperties */: // fallthrough case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; @@ -16877,12 +17077,13 @@ var ts; case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected; case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; + case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected; case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 18 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; - case 19 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 20 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; - case 21 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; - case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; + case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; + case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; + case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` @@ -17082,7 +17283,7 @@ var ts; var node = createNode(162 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } return finishNode(node); } @@ -17180,7 +17381,7 @@ var ts; } function parseJSDocType() { var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); - var type = parseType(); + var type = parseTypeOrTypePredicate(); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -17226,7 +17427,7 @@ var ts; } function parseTypeParameters() { if (token() === 27 /* LessThanToken */) { - return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } } function parseParameterType() { @@ -17235,12 +17436,12 @@ var ts; } return undefined; } - function isStartOfParameter() { + function isStartOfParameter(isJSDocParameter) { return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 /* AtToken */ || - isStartOfType(/*inStartOfParameter*/ true); + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); } function parseParameter() { var node = createNodeWithJSDoc(149 /* Parameter */); @@ -17326,7 +17527,9 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1 /* Yield */)); setAwaitContext(!!(flags & 2 /* Await */)); - signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + signature.parameters = flags & 32 /* JSDoc */ ? + parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) : + parseDelimitedList(16 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return parseExpected(20 /* CloseParenToken */); @@ -17564,7 +17767,7 @@ var ts; } function parseTupleType() { var node = createNode(168 /* TupleType */); - node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { @@ -17717,6 +17920,8 @@ var ts; case 126 /* InferKeyword */: case 91 /* ImportKeyword */: return true; + case 89 /* FunctionKeyword */: + return !inStartOfParameter; case 38 /* MinusToken */: return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19 /* OpenParenToken */: @@ -17729,7 +17934,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 20 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); } function parsePostfixTypeOrHigher() { var type = parseNonArrayType(); @@ -18223,8 +18428,9 @@ var ts; return 1 /* True */; } // If we had "(" followed by something that's not an identifier, - // then this definitely doesn't look like a lambda. - if (!isIdentifier()) { + // then this definitely doesn't look like a lambda. "this" is not + // valid, but we want to parse it and then give a semantic error. + if (!isIdentifier() && second !== 99 /* ThisKeyword */) { return 0 /* False */; } switch (nextToken()) { @@ -19059,7 +19265,7 @@ var ts; } else { var argument = allowInAnd(parseExpression); - if (ts.isStringOrNumericLiteral(argument)) { + if (ts.isStringOrNumericLiteralLike(argument)) { argument.text = internIdentifier(argument.text); } indexedAccess.argumentExpression = argument; @@ -19130,7 +19336,7 @@ var ts; if (!parseOptional(27 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; @@ -20282,7 +20488,7 @@ var ts; // ClassTail[Yield,Await] : (Modified) See 14.5 // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } if (isHeritageClause()) { - return parseList(21 /* HeritageClauses */, parseHeritageClause); + return parseList(22 /* HeritageClauses */, parseHeritageClause); } return undefined; } @@ -20303,7 +20509,7 @@ var ts; } function tryParseTypeArguments() { return token() === 27 /* LessThanToken */ - ? parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) + ? parseBracketedList(20 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */) : undefined; } function isHeritageClause() { @@ -20529,7 +20735,7 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { @@ -20643,13 +20849,14 @@ var ts; ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren"; ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers"; ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters"; - ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties"; - ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 23] = "Count"; // Number of parsing contexts + ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters"; + ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties"; + ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -20766,7 +20973,7 @@ var ts; switch (token()) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -20826,7 +21033,7 @@ var ts; nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return createJSDocComment(); }); function removeLeadingNewlines(comments) { @@ -20834,8 +21041,8 @@ var ts; comments.shift(); } } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + function removeTrailingWhitespace(comments) { + while (comments.length && comments[comments.length - 1].trim() === "") { comments.pop(); } } @@ -20867,13 +21074,30 @@ var ts; nextJSDocToken(); } } + function skipWhitespaceOrAsterisk() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } + var precedingLineBreak = scanner.hasPrecedingLineBreak(); + while ((precedingLineBreak && token() === 39 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (token() === 4 /* NewLineTrivia */) { + precedingLineBreak = true; + } + else if (token() === 39 /* AsteriskToken */) { + precedingLineBreak = false; + } + nextJSDocToken(); + } + } function parseTag(indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); var tagName = parseJSDocIdentifierName(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { case "augments": @@ -20887,6 +21111,9 @@ var ts; case "this": tag = parseThisTag(atToken, tagName); break; + case "enum": + tag = parseEnumTag(atToken, tagName); + break; case "arg": case "argument": case "param": @@ -20984,7 +21211,7 @@ var ts; tok = nextJSDocToken(); } removeLeadingNewlines(comments); - removeTrailingNewlines(comments); + removeTrailingWhitespace(comments); return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { @@ -21007,7 +21234,7 @@ var ts; tagsEnd = tag.end; } function tryParseTypeExpression() { - skipWhitespace(); + skipWhitespaceOrAsterisk(); return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { @@ -21041,15 +21268,15 @@ var ts; function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; - skipWhitespace(); + skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; skipWhitespace(); if (isNameFirst) { typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(302 /* JSDocPropertyTag */, atToken.pos) : - createNode(296 /* JSDocParameterTag */, atToken.pos); + createNode(303 /* JSDocPropertyTag */, atToken.pos) : + createNode(297 /* JSDocParameterTag */, atToken.pos); var comment; if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); @@ -21075,7 +21302,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { - if (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) { + if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } } @@ -21091,20 +21318,20 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 297 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 298 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(297 /* JSDocReturnTag */, atToken.pos); + var result = createNode(298 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 299 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(299 /* JSDocTypeTag */, atToken.pos); + var result = createNode(300 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); @@ -21145,7 +21372,15 @@ var ts; return finishNode(tag); } function parseThisTag(atToken, tagName) { - var tag = createNode(298 /* JSDocThisTag */, atToken.pos); + var tag = createNode(299 /* JSDocThisTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseEnumTag(atToken, tagName) { + var tag = createNode(296 /* JSDocEnumTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); @@ -21155,7 +21390,7 @@ var ts; function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(301 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); @@ -21168,12 +21403,12 @@ var ts; var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; - var start_3 = scanner.getStartPos(); + var start_3 = atToken.pos; while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 299 /* JSDocTypeTag */) { + if (child.kind === 300 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -21236,7 +21471,7 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(57 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 297 /* JSDocReturnTag */) { + if (tag && tag.kind === 298 /* JSDocReturnTag */) { return tag; } } @@ -21281,7 +21516,7 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) && + if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -21350,16 +21585,14 @@ var ts; skipWhitespace(); var typeParameter = createNode(148 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); - skipWhitespace(); finishNode(typeParameter); + skipWhitespace(); typeParameters.push(typeParameter); } while (parseOptionalJsdoc(26 /* CommaToken */)); - if (constraint) { - ts.first(typeParameters).constraint = constraint.type; - } - var result = createNode(300 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(301 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; + result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); return result; @@ -21885,9 +22118,11 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + ts.isDeclarationFileName = isDeclarationFileName; /*@internal*/ function processCommentPragmas(context, sourceText) { var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); @@ -22431,13 +22666,15 @@ var ts; { name: "noImplicitAny", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type }, { name: "strictNullChecks", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_null_checks @@ -22445,6 +22682,7 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types @@ -22452,6 +22690,7 @@ var ts; { name: "strictPropertyInitialization", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes @@ -22459,6 +22698,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, @@ -22466,6 +22706,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file @@ -22474,6 +22715,7 @@ var ts; { name: "noUnusedLocals", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_locals, @@ -22481,6 +22723,7 @@ var ts; { name: "noUnusedParameters", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_on_unused_parameters, @@ -22488,6 +22731,7 @@ var ts; { name: "noImplicitReturns", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value @@ -22495,6 +22739,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement @@ -22565,12 +22810,14 @@ var ts; { name: "allowSyntheticDefaultImports", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, { name: "esModuleInterop", type: "boolean", + affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports @@ -22746,6 +22993,7 @@ var ts; { name: "noImplicitUseStrict", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output }, @@ -22784,24 +23032,28 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels }, { name: "allowUnreachableCode", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code }, { name: "suppressExcessPropertyErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, }, { name: "suppressImplicitAnyIndexErrors", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, }, @@ -22820,6 +23072,7 @@ var ts; { name: "noStrictGenericChecks", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, }, @@ -23341,9 +23594,10 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); - var option = knownOptions ? knownOptions.get(keyText) : undefined; - if (extraKeyDiagnosticMessage && !option) { + var textOfKey = ts.getTextOfPropertyName(element.name); + var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); + var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; + if (keyText && extraKeyDiagnosticMessage && !option) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); @@ -24418,9 +24672,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -24649,9 +24903,7 @@ var ts; return perFolderCache; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; // TODO: GH#18217 - } + ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { perModuleNameCache = createPerModuleNameCache(); @@ -24683,41 +24935,45 @@ var ts; return; } directoryPathMap.set(path, result); - var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + var resolvedFileName = result.resolvedModule && + (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName); // find common prefix between directory and resolved file name - // this common prefix should be the shorted path that has the same resolution + // this common prefix should be the shortest path that has the same resolution // directory: /a/b/c/d/e // resolvedFileName: /a/b/foo.d.ts - var commonPrefix = getCommonPrefix(path, resolvedFileName); + // commonPrefix: /a/b + // for failed lookups cache the result for every directory up to root + var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName); var current = path; - while (true) { + while (current !== commonPrefix) { var parent = ts.getDirectoryPath(current); if (parent === current || directoryPathMap.has(parent)) { break; } directoryPathMap.set(parent, result); current = parent; - if (current === commonPrefix) { - break; - } } } function getCommonPrefix(directory, resolution) { - if (resolution === undefined) { - return undefined; - } var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); // find first position where directory and resolution differs var i = 0; - while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + var limit = Math.min(directory.length, resolutionDirectory.length); + while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { i++; } - // find last directory separator before position i - var sep = directory.lastIndexOf(ts.directorySeparator, i); - if (sep < 0) { + if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) { + return directory; + } + var rootLength = ts.getRootLength(directory); + if (i < rootLength) { return undefined; } - return directory.substr(0, sep); + var sep = directory.lastIndexOf(ts.directorySeparator, i - 1); + if (sep === -1) { + return undefined; + } + return directory.substr(0, Math.max(sep, rootLength)); } } } @@ -24766,10 +25022,9 @@ var ts; } if (perFolderCache) { perFolderCache.set(moduleName, result); - // put result in per-module name cache - var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); - if (perModuleNameCache) { - perModuleNameCache.set(containingDirectory, result); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // put result in per-module name cache + cache.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); } } } @@ -24994,15 +25249,15 @@ var ts; tryResolve(Extensions.JavaScript) || (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); + return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { @@ -25012,17 +25267,13 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - var originalPath = void 0; - if (!compilerOptions.preserveSymlinks && resolvedValue) { - originalPath = resolvedValue.path; + if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) { var path = realPath(resolvedValue.path, host, traceEnabled); - if (path === originalPath) { - originalPath = undefined; - } - resolvedValue = __assign({}, resolvedValue, { path: path }); + var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path; + resolvedValue = __assign({}, resolvedValue, { path: path, originalPath: originalPath }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -25075,7 +25326,8 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } - var nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + ts.nodeModulesPathPart = "/node_modules/"; /** * This will be called on the successfully resolved path from `loadModuleFromFile`. * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) @@ -25089,11 +25341,11 @@ var ts; */ function parseNodeModuleFromPath(resolved) { var path = ts.normalizePath(resolved.path); - var idx = path.lastIndexOf(nodeModulesPathPart); + var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; } - var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length; var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); @@ -25436,7 +25688,7 @@ var ts; trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { @@ -25446,17 +25698,17 @@ var ts; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*originalPath*/ undefined, /*isExternalLibraryImport*/ false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (!ts.isExternalModuleNameRelative(moduleName)) { + var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); if (resolutionFromCache) { return resolutionFromCache; } @@ -25491,7 +25743,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*originalPath*/ undefined, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -25699,10 +25951,10 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; symbol.declarations = ts.append(symbol.declarations, node); - if (symbolFlags & 1955 /* HasExports */ && !symbol.exports) { + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } - if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } if (symbolFlags & 67216319 /* Value */) { @@ -25729,7 +25981,7 @@ var ts; if (name.kind === 147 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression)) { + if (ts.isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); @@ -25774,7 +26026,7 @@ var ts; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); // TODO: GH#18217 + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); } /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @@ -25845,8 +26097,10 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; } if (symbol.declarations && symbol.declarations.length) { // If the current node is a default export of some sort, then check if @@ -25854,6 +26108,7 @@ var ts; // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } else { // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. @@ -25863,13 +26118,15 @@ var ts; if (symbol.declarations && symbol.declarations.length && (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; } } } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); symbol = createSymbol(0 /* None */, name); } } @@ -26140,7 +26397,7 @@ var ts; case 189 /* CallExpression */: bindCallExpressionFlow(node); break; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; @@ -26165,6 +26422,7 @@ var ts; case 71 /* Identifier */: case 99 /* ThisKeyword */: case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return isNarrowableReference(expr); case 189 /* CallExpression */: return hasNarrowableArgument(expr); @@ -26178,10 +26436,11 @@ var ts; return false; } function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || - expr.kind === 99 /* ThisKeyword */ || - expr.kind === 97 /* SuperKeyword */ || - expr.kind === 187 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + return expr.kind === 71 /* Identifier */ || expr.kind === 99 /* ThisKeyword */ || expr.kind === 97 /* SuperKeyword */ || + ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + ts.isElementAccessExpression(expr) && expr.argumentExpression && + (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && + isNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -26617,7 +26876,7 @@ var ts; bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { - errorOrSuggestionOnFirstToken(ts.unusedLabelIsError(options), node, ts.Diagnostics.Unused_label); + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); } if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { // do statement sets current flow inside bindDoStatement @@ -26906,7 +27165,7 @@ var ts; case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: case 287 /* JSDocFunctionType */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: case 240 /* TypeAliasDeclaration */: case 179 /* MappedType */: @@ -27244,13 +27503,26 @@ var ts; errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } + function checkStrictModeLabeledStatement(node) { + // Grammar checking for labeledStatement + if (inStrictMode && options.target >= 2 /* ES2015 */) { + if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) { + errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here); + } + } + } function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } - function errorOrSuggestionOnFirstToken(isError, node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - var diag = ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2); + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); if (isError) { file.bindDiagnostics.push(diag); } @@ -27370,12 +27642,19 @@ var ts; } return checkStrictModeIdentifier(node); case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: if (currentFlow && isNarrowableReference(node)) { node.flowNode = currentFlow; } if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } + if (ts.isInJavaScriptFile(node) && + file.commonJsModuleIndicator && + ts.isModuleExportsPropertyAccessExpression(node) && + !lookupSymbolForNameWorker(container, "module")) { + declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + } break; case 202 /* BinaryExpression */: var specialKind = ts.getSpecialPropertyAssignmentKind(node); @@ -27417,6 +27696,8 @@ var ts; return checkStrictModePrefixUnaryExpression(node); case 229 /* WithStatement */: return checkStrictModeWithStatement(node); + case 231 /* LabeledStatement */: + return checkStrictModeLabeledStatement(node); case 176 /* ThisType */: seenThisKeyword = true; return; @@ -27520,7 +27801,7 @@ var ts; // falls through case 243 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: if (node.parent.kind === 291 /* JSDocSignature */) { return bindParameter(node); } @@ -27528,13 +27809,13 @@ var ts; break; } // falls through - case 302 /* JSDocPropertyTag */: + case 303 /* JSDocPropertyTag */: var propTag = node; var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } @@ -27739,6 +28020,11 @@ var ts; } function bindSpecialPropertyAssignment(node) { var lhs = node.left; + // Class declarations in Typescript do not allow property declarations + var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); + if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + return; + } // Fix up parent pointers since we're going to use these nodes before we bind into them node.left.parent = node; node.right.parent = node; @@ -27922,7 +28208,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 296 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + if (node.kind === 297 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -28046,18 +28332,48 @@ var ts; // - node is not block scoped variable statement and at least one variable declaration has initializer // Rationale: we don't want to report errors on non-initialized var's since they are hoisted // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var isError = ts.unreachableCodeIsError(options) && + var isError_1 = ts.unreachableCodeIsError(options) && !(node.flags & 4194304 /* Ambient */) && (!ts.isVariableStatement(node) || !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || node.declarationList.declarations.some(function (d) { return !!d.initializer; })); - errorOrSuggestionOnFirstToken(isError, node, ts.Diagnostics.Unreachable_code_detected); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); } } } return true; } } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return true; + case 242 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 241 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } /* @internal */ function isExportsOrModuleExportsOrAlias(sourceFile, node) { return ts.isExportsIdentifier(node) || @@ -28631,7 +28947,7 @@ var ts; break; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 3 /* AssertTypeScript */; excludeFlags = 536872257 /* OuterExpressionExcludes */; @@ -28908,7 +29224,7 @@ var ts; return 940049729 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: case 193 /* ParenthesizedExpression */: case 97 /* SuperKeyword */: return 536872257 /* OuterExpressionExcludes */; @@ -28932,7 +29248,7 @@ var ts; /** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -29008,7 +29324,7 @@ var ts; ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { - visitType(getConstraintFromTypeParameter(type)); + visitType(getConstraintOfTypeParameter(type)); } function visitUnionOrIntersectionType(type) { ts.forEach(type.types, visitType); @@ -29080,7 +29396,7 @@ var ts; } var t = getTypeOfSymbol(symbol); visitType(t); // Should handle members on classes and such - if (symbol.flags & 1955 /* HasExports */) { + if (symbol.exports) { symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { @@ -29170,7 +29486,6 @@ var ts; undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); - var moduleSymbol = createSymbol(4 /* Property */, "module"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; // for public members that accept a Node or one of its subtypes, we must guard against @@ -29214,6 +29529,7 @@ var ts; return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, + getPromisedTypeOfPromise: getPromisedTypeOfPromise, getReturnTypeOfSignature: getReturnTypeOfSignature, getNullableType: getNullableType, getNonNullableType: getNonNullableType, @@ -29282,6 +29598,10 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, + getContextualTypeForObjectLiteralElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); + return node ? getContextualTypeForObjectLiteralElement(node) : undefined; + }, getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); @@ -29292,12 +29612,11 @@ var ts; }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { - var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); - apparentArgumentCount = theArgumentCount; - var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; - apparentArgumentCount = undefined; - return res; + getResolvedSignature: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + }, + getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); }, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); @@ -29334,7 +29653,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); @@ -29377,7 +29696,7 @@ var ts; getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentModule: function (node, target) { return getSuggestionForNonexistentModule(node, target); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -29396,6 +29715,9 @@ var ts; return node && getTypeArgumentConstraint(node); }, getSuggestionDiagnostics: function (file, ct) { + if (ts.skipTypeChecking(file, compilerOptions)) { + return ts.emptyArray; + } var diagnostics; try { // Record the cancellation token so it can be checked later on during checkSourceElement. @@ -29415,8 +29737,8 @@ var ts; cancellationToken = undefined; } function addUnusedDiagnostics() { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) { - if (!unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); } }); @@ -29432,6 +29754,13 @@ var ts; } } }; + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); + apparentArgumentCount = argumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + apparentArgumentCount = undefined; + return res; + } var tupleTypes = ts.createMap(); var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); @@ -29487,7 +29816,6 @@ var ts; var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); @@ -29659,7 +29987,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30101,6 +30429,7 @@ var ts; // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ) // or if usage is in a type context: // 1. inside a type query (typeof in type position) + // 2. inside a jsdoc comment if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; @@ -30110,7 +30439,7 @@ var ts; return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { @@ -30393,7 +30722,7 @@ var ts; location = location.parent; } break; - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); @@ -30427,10 +30756,6 @@ var ts; if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } - if (ts.isIdentifier(originalLocation) && ts.isPropertyAccessExpression(originalLocation.parent) && - originalLocation.escapedText === "module" && originalLocation.parent.name.escapedText === "exports") { - return moduleSymbol; - } } } if (!result) { @@ -30443,9 +30768,13 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { - suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } } if (!suggestion) { @@ -30654,7 +30983,7 @@ var ts; ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } } @@ -30798,7 +31127,7 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } } } @@ -30833,9 +31162,13 @@ var ts; if (!symbol) { var moduleName = getFullyQualifiedName(moduleSymbol); var declarationName = ts.declarationNameToString(name); - var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); @@ -31157,6 +31490,12 @@ var ts; var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); } + else if (!compilerOptions.resolveJsonModule && + ts.fileExtensionIs(moduleReference, ".json" /* Json */) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -31169,8 +31508,8 @@ var ts; var errorInfo = packageId ? ts.chainDiagnosticMessages( /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0 - : ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)) + ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 + : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } @@ -31315,13 +31654,13 @@ var ts; } function getExportsOfModuleWorker(moduleSymbol) { var visitedSymbols = []; - // A module defined by an 'export=' consists on one export that needs to be resolved + // A module defined by an 'export=' consists of one export that needs to be resolved moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; // 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 & 1955 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { return; } var symbols = ts.cloneMap(symbol.exports); @@ -31366,17 +31705,25 @@ var ts; * Attempts to find the symbol corresponding to the container a symbol is in - usually this * is just its' `.parent`, but for locals, this value is `undefined` */ - function getContainerOfSymbol(symbol) { + function getContainersOfSymbol(symbol, enclosingDeclaration) { var container = getParentOfSymbol(symbol); if (container) { - return container; + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + } + return ts.append(additionalContainers, container); } - var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); - if (!candidate) { + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { return undefined; } - var alias = getAliasForSymbolInContainer(candidate, symbol); - return alias ? candidate : undefined; + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { @@ -31400,9 +31747,7 @@ var ts; } } function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; + return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); @@ -31627,6 +31972,54 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -31637,55 +32030,20 @@ var ts; */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, - }; - } - return hasAccessibleDeclarations; - } - else { - if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { - // Any meaning of a module symbol is always accessible via an `import` type - return { - accessibility: 0 /* Accessible */ - }; - } - } - // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. - // It could be a qualified symbol and hence verify the path - // e.g.: - // module m { - // export class c { - // } - // } - // const x: typeof m.c - // In the above example when we start with checking if typeof m.c symbol is accessible, - // we are going to see if c can be accessed in scope directly. - // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible - // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getContainerOfSymbol(symbol); + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { accessibility: 2 /* CannotBeNamed */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), errorModuleName: symbolToString(symbolExternalModule) }; } @@ -31693,14 +32051,14 @@ var ts; // Just a local name that is not accessible return { accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 /* Accessible */ }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); @@ -31821,7 +32179,8 @@ var ts; function typeToString(type, enclosingDeclaration, flags, writer) { if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); if (typeNode === undefined) return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; @@ -31829,7 +32188,7 @@ var ts; var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } @@ -31874,11 +32233,17 @@ var ts; tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, visitedSymbols: undefined, - inferTypeParameters: undefined + inferTypeParameters: undefined, + approximateLength: 0 }; var resultingNode = cb(context); return context.encounteredError ? undefined : resultingNode; } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + } function typeToTypeNodeHelper(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); @@ -31890,66 +32255,83 @@ var ts; return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } if (type.flags & 2 /* Unknown */) { return ts.createKeywordTypeNode(142 /* UnknownKeyword */); } if (type.flags & 4 /* String */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(137 /* StringKeyword */); } if (type.flags & 8 /* Number */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(134 /* NumberKeyword */); } if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (type.flags & (64 /* StringLiteral */)) { + if (type.flags & 64 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & (128 /* NumberLiteral */)) { + if (type.flags & 128 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } if (type.flags & 256 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 2048 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + context.approximateLength += 6; return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } + context.approximateLength += 13; return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); } if (type.flags & 4096 /* Void */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(105 /* VoidKeyword */); } if (type.flags & 8192 /* Undefined */) { + context.approximateLength += 9; return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); } if (type.flags & 16384 /* Null */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(95 /* NullKeyword */); } if (type.flags & 32768 /* Never */) { + context.approximateLength += 5; return ts.createKeywordTypeNode(131 /* NeverKeyword */); } if (type.flags & 1024 /* ESSymbol */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(138 /* SymbolKeyword */); } if (type.flags & 16777216 /* NonPrimitive */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(135 /* ObjectKeyword */); } if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { @@ -31961,6 +32343,7 @@ var ts; context.tracker.reportInaccessibleThisError(); } } + context.approximateLength += 4; return ts.createThis(); } var objectFlags = ts.getObjectFlags(type); @@ -31970,6 +32353,7 @@ var ts; } if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && @@ -31978,7 +32362,9 @@ var ts; ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context) && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { - return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol @@ -31993,7 +32379,7 @@ var ts; } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; - var typeNodes = mapToTypeNodes(types, context); + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; @@ -32012,12 +32398,14 @@ var ts; } if (type.flags & 1048576 /* Index */) { var indexedType = type.type; + context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } if (type.flags & 2097152 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } if (type.flags & 4194304 /* Conditional */) { @@ -32028,6 +32416,7 @@ var ts; context.inferTypeParameters = saveInferTypeParameters; var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 8388608 /* Substitution */) { @@ -32050,6 +32439,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { @@ -32058,7 +32448,7 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); @@ -32077,6 +32467,7 @@ var ts; return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); } else { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } } @@ -32118,6 +32509,7 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { @@ -32136,6 +32528,7 @@ var ts; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function typeReferenceToTypeNode(type) { @@ -32252,6 +32645,9 @@ var ts; return ids; } function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; @@ -32274,8 +32670,10 @@ var ts; if (!properties) { return typeElements; } + var i = 0; for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + i++; if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { if (propertySymbol.flags & 4194304 /* Prototype */) { continue; @@ -32284,61 +32682,96 @@ var ts; context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); } } - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? - anyType : getTypeOfSymbol(propertySymbol); - var saveEnclosingDeclaration = context.enclosingDeclaration; - context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } - } + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); - context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; - if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { - var signatures = getSignaturesOfType(propertyType, 0 /* Call */); - for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { - var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); - } - typeElements.push(methodDeclaration); - } + addPropertyToElementList(propertySymbol, context, typeElements); + } + return typeElements.length ? typeElements : undefined; + } + } + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); } - else { - var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; - var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined); - if (propertySymbol.valueDeclaration) { - // Copy comments to node for declaration emit - ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); - } - typeElements.push(propertySignature); + } + } + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); } + typeElements.push(methodDeclaration); } - return typeElements.length ? typeElements : undefined; + } + else { + var savedFlags = context.flags; + context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); } } - function mapToTypeNodes(types, context) { + function mapToTypeNodes(types, context, isBareList) { if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } var result = []; + var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -32360,6 +32793,7 @@ var ts; if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } + context.approximateLength += (name.length + 4); return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } @@ -32398,6 +32832,7 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { @@ -32419,14 +32854,14 @@ var ts; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 296 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 297 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -32448,6 +32883,7 @@ var ts; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); @@ -32477,16 +32913,18 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); - var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents)) { + for (var _i = 0, _a = parents; _i < _a.length; _i++) { + var parent = _a[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } } } } @@ -32496,10 +32934,12 @@ var ts; if ( // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol))) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } return [symbol]; } } @@ -32554,24 +32994,26 @@ var ts; } } } - return symbol.escapedName.substring(1, symbol.escapedName.length - 1); - } - else { - if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { - // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); - var links = getSymbolLinks(symbol); - var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); - if (!specifier) { - specifier = ts.flatten(ts.moduleSpecifiers.getModuleSpecifiers(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, context.tracker.moduleResolverHost.getSourceFiles(), // TODO: GH#18217 - { importModuleSpecifierPreference: "non-relative" }))[0]; - links.specifierCache = links.specifierCache || ts.createMap(); - links.specifierCache.set(contextFile.path, specifier); + } + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + if (ambientModuleSymbolRegex.test(symbol.escapedName)) { + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); } - return specifier; + return ts.getSourceFileOfNode(ts.getNonAugmentationDeclaration(symbol)).fileName; // A resolver may not be provided for baselines and errors - in those cases we use the fileName in full + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); } + return specifier; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module @@ -32580,7 +33022,11 @@ var ts; // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); - var lit = ts.createLiteralTypeNode(ts.createLiteral(getSpecifierForModuleSymbol(chain[0], context))); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) + context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + context.approximateLength += specifier.length + 10; // specifier + import("") if (!nonRootParts || ts.isEntityName(nonRootParts)) { if (nonRootParts) { var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; @@ -32614,6 +33060,7 @@ var ts; context.flags |= 16777216 /* InInitialEntityName */; } var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } @@ -32828,7 +33275,7 @@ var ts; function determineIfDeclarationIsVisible() { switch (node.kind) { case 295 /* JSDocCallbackTag */: - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); @@ -32981,23 +33428,19 @@ var ts; return -1; } function hasType(target, propertyName) { - if (propertyName === 0 /* Type */) { - return !!getSymbolLinks(target).type; - } - if (propertyName === 2 /* DeclaredType */) { - return !!getSymbolLinks(target).declaredType; - } - if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return !!target.resolvedBaseConstructorType; - } - if (propertyName === 3 /* ResolvedReturnType */) { - return !!target.resolvedReturnType; - } - if (propertyName === 4 /* ResolvedBaseConstraint */) { - var bc = target.resolvedBaseConstraint; - return !!bc && bc !== circularConstraintType; - } - return ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; + } + return ts.Debug.assertNever(propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -33044,7 +33487,7 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); @@ -33062,10 +33505,9 @@ var ts; } for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { var prop = _b[_a]; - var inNamesToRemove = names.has(prop.escapedName); - var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); - var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); - if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { + if (!names.has(prop.escapedName) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { members.set(prop.escapedName, getNonReadonlySymbol(prop)); } } @@ -33273,17 +33715,17 @@ var ts; } } // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.escapedName === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } + else if (ts.isInJavaScriptFile(declaration)) { + var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); + if (expandoType) { + return expandoType; + } + } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); @@ -33301,96 +33743,46 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); if (specialDeclaration) { - return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var tag = ts.getJSDocTypeTag(specialDeclaration); + if (tag && tag.typeExpression) { + return getTypeFromTypeNode(tag.typeExpression); + } + var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); + return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); } - var types = []; - var constructorTypes; var definedInConstructor = false; var definedInMethod = false; - var jsDocType; - var _loop_4 = function (declaration) { - var declarationInConstructor = false; + var jsdocType; + var types; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; var expression = ts.isBinaryExpression(declaration) ? declaration : ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { - return { value: errorType }; + return errorType; } var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); if (special === 4 /* ThisProperty */) { - var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); - // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. - // Function expressions that are assigned to the prototype count as methods. - declarationInConstructor = thisContainer.kind === 155 /* Constructor */ || - thisContainer.kind === 237 /* FunctionDeclaration */ || - (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); - if (declarationInConstructor) { + if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } else { definedInMethod = true; } } - // If there is a JSDoc type, use it - var type_1 = getTypeForDeclarationFromJSDocComment(expression.parent); - if (type_1) { - var declarationType = getWidenedType(type_1); - if (!jsDocType) { - jsDocType = declarationType; - } - else if (jsDocType !== errorType && declarationType !== errorType && - !isTypeIdenticalTo(jsDocType, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { - errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); - } - } - else if (!jsDocType && ts.isBinaryExpression(expression)) { - // If we don't have an explicit JSDoc type, get the type from the expression. - var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); - if (ts.getObjectFlags(type_2) & 16 /* Anonymous */ && - special === 2 /* ModuleExports */ && - symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type_2); - var members_3 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_3); - symbol.exports.forEach(function (s, name) { - if (members_3.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_3.set(name, union); - } - else { - members_3.set(name, s); - } - }); - type_2 = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); - } - var anyedType = type_2; - if (isEmptyArrayLiteralType(type_2)) { - anyedType = anyArrayType; - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } - } - types.push(anyedType); - if (declarationInConstructor) { - (constructorTypes || (constructorTypes = [])).push(anyedType); - } + jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + if (!jsdocType) { + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); } - }; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var state_2 = _loop_4(declaration); - if (typeof state_2 === "object") - return state_2.value; } - var type = jsDocType; + var type = jsdocType; if (!type) { + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfSpecialPropertyOfBaseType(symbol); @@ -33411,6 +33803,91 @@ var ts; } return widened; } + function getJSExpandoObjectType(decl, symbol, init) { + if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + return undefined; + } + var exports = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports, s.exports); + } + var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + type.objectFlags |= 16384 /* JSLiteral */; + return type; + } + function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + var typeNode = ts.getJSDocType(expression.parent); + if (typeNode) { + var type = getWidenedType(getTypeFromTypeNode(typeNode)); + if (!declaredType) { + return type; + } + else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) { + errorNextVariableOrPropertyDeclarationMustHaveSameType(declaredType, declaration, type); + } + } + return declaredType; + } + /** If we don't have an explicit JSDoc type, get the type from the initializer. */ + function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); + if (type.flags & 131072 /* Object */ && + special === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + if (resolvedSymbol && !resolvedSymbol.exports) { + resolvedSymbol.exports = ts.createSymbolTable(); + } + (resolvedSymbol || symbol).exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + var result = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + return result; + } + if (isEmptyArrayLiteralType(type)) { + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + return anyArrayType; + } + return type; + } + function isDeclarationInConstructor(expression) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + return thisContainer.kind === 155 /* Constructor */ || + thisContainer.kind === 237 /* FunctionDeclaration */ || + (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + } + function getConstructorDefinedThisAssignmentTypes(types, declarations) { + ts.Debug.assert(types.length === declarations.length); + return types.filter(function (_, i) { + var declaration = declarations[i]; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined; + return expression && isDeclarationInConstructor(expression); + }); + } /** check for definition in base class if any declaration is in a class */ function getTypeOfSpecialPropertyOfBaseType(specialProperty) { var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { @@ -33548,138 +34025,104 @@ var ts; } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - // Handle prototype property - if (symbol.flags & 4194304 /* Prototype */) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - // CommonsJS require and module both have type any. - if (symbol === requireSymbol || symbol === moduleSymbol) { - return links.type = anyType; - } - // Handle catch clause variables - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; - } - if (declaration.kind === 252 /* ExportAssignment */) { - return links.type = checkExpression(declaration.expression); - } - // Handle variable, parameter or property - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; - } - var type = getJSSpecialType(symbol, declaration); - if (!type) { - if (ts.isJSDocPropertyLikeTag(declaration) - || ts.isPropertyAccessExpression(declaration) - || ts.isIdentifier(declaration) - || ts.isClassDeclaration(declaration) - || ts.isFunctionDeclaration(declaration) - || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { - // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - return getTypeOfFuncClassEnumModule(symbol); - } - type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; - } - else if (ts.isPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); - } - else if (ts.isJsxAttribute(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); - } - else if (ts.isShorthandPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); - } - else if (ts.isObjectLiteralMethod(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); - } - else if (ts.isParameter(declaration) - || ts.isPropertyDeclaration(declaration) - || ts.isPropertySignature(declaration) - || ts.isVariableDeclaration(declaration) - || ts.isBindingElement(declaration)) { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); - } - else { - return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); - } - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; + return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); } - function getJSSpecialType(symbol, decl) { - if (!ts.isInJavaScriptFile(decl)) { - return undefined; + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return getTypeOfPrototypeProperty(symbol); + } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol) { + return anyType; + } + if (symbol.flags & 134217728 /* ModuleExports */) { + var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var members = ts.createSymbolTable(); + members.set("exports", fileSymbol); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return anyType; + } + // Handle export default expressions + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; } - else if (ts.isJSDocPropertyLikeTag(decl) && decl.typeExpression) { - return getTypeFromTypeNode(decl.typeExpression.type); - } - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - else if (ts.isBinaryExpression(decl) || - ts.isPropertyAccessExpression(decl) && ts.isBinaryExpression(decl.parent)) { - return getJSInitializerType(decl, symbol, ts.getAssignedJavascriptInitializer(ts.isBinaryExpression(decl) ? decl.left : decl)) || - getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else if (ts.isParameter(decl) - || ts.isPropertyDeclaration(decl) - || ts.isPropertySignature(decl) - || ts.isVariableDeclaration(decl) - || ts.isBindingElement(decl)) { - // Use type from type annotation if one is present - var isOptional = ts.isParameter(decl) && isJSDocOptionalParameter(decl) || - !ts.isBindingElement(decl) && !ts.isVariableDeclaration(decl) && !!decl.questionToken; - var declaredType = tryGetTypeFromEffectiveTypeNode(decl); - return declaredType && addOptionality(declaredType, isOptional) || - getJSInitializerType(decl, symbol, ts.getDeclaredJavascriptInitializer(decl)) || - getWidenedTypeForVariableLikeDeclaration(decl, /*includeOptionality*/ true); - } - } - function getJSInitializerType(decl, symbol, init) { - if (init && ts.isInJavaScriptFile(init) && ts.isObjectLiteralExpression(init)) { - var exports_1 = ts.createSymbolTable(); - while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { - var s_1 = getSymbolOfNode(decl); - if (s_1 && ts.hasEntries(s_1.exports)) { - mergeSymbolTable(exports_1, s_1.exports); - } - decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; - } - var s = getSymbolOfNode(decl); - if (s && ts.hasEntries(s.exports)) { - mergeSymbolTable(exports_1, s.exports); - } - return createAnonymousType(symbol, exports_1, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + if (declaration.kind === 252 /* ExportAssignment */) { + return checkExpression(declaration.expression); } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + if (ts.isInJavaScriptFile(declaration) && + (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { + type = getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = ts.isBinaryExpression(declaration.parent) ? + getWidenedTypeFromJSPropertyAssignments(symbol) : + tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + return type; } - function getAnnotatedAccessorType(accessor) { + function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { if (accessor.kind === 156 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); - return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + return getterTypeAnnotation; } else { var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + return setterTypeAnnotation; } } return undefined; } + function getAnnotatedAccessorType(accessor) { + var node = getAnnotatedAccessorTypeNode(accessor); + return node && getTypeFromTypeNode(node); + } function getAnnotatedAccessorThisParameter(accessor) { var parameter = getAccessorThisParameter(accessor); return parameter && parameter.symbol; @@ -33689,60 +34132,60 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + } + function getTypeOfAccessorsWorker(symbol) { + var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return jsDocType; } - var type = void 0; - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; } else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); } + // Otherwise, fall back to 'any'. else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } - type = anyType; } + type = anyType; } } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); - error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); - } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } - links.type = type; } - return links.type; + return type; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); @@ -33750,6 +34193,7 @@ var ts; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); + var originalLinks = links; if (!links.type) { var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); if (jsDeclaration) { @@ -33768,32 +34212,45 @@ var ts; } } } - if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else if (symbol.valueDeclaration.kind === 202 /* BinaryExpression */ || - symbol.valueDeclaration.kind === 187 /* PropertyAccessExpression */ && symbol.valueDeclaration.parent.kind === 202 /* BinaryExpression */) { - links.type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - var type = createObjectType(16 /* Anonymous */, symbol); - if (symbol.flags & 32 /* Class */) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol); + } + return links.type; + } + function getTypeOfFuncClassEnumModuleWorker(symbol) { + var declaration = symbol.valueDeclaration; + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + return anyType; + } + else if (declaration.kind === 202 /* BinaryExpression */ || + declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { + return getWidenedTypeFromJSPropertyAssignments(symbol); + } + else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { + var resolvedModule = resolveExternalModuleSymbol(symbol); + if (resolvedModule !== symbol) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; } - else { - links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); + var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + if (!popTypeResolution()) { + return reportCircularityError(symbol); } + return type_1; } } - return links.type; + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type; + } } function getTypeOfEnumMember(symbol) { var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; + return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol)); } function getTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); @@ -33819,7 +34276,7 @@ var ts; } else { if (!pushTypeResolution(symbol, 0 /* Type */)) { - return errorType; + return links.type = errorType; } symbolInstantiationDepth++; var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); @@ -33923,8 +34380,8 @@ var ts; case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: case 240 /* TypeAliasDeclaration */: - case 300 /* JSDocTemplateTag */: - case 301 /* JSDocTypedefTag */: + case 301 /* JSDocTemplateTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: case 179 /* MappedType */: case 173 /* ConditionalType */: @@ -33987,15 +34444,18 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return false; + return isJavascriptConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + var isJavascript = ts.isInJavaScriptFile(location); + if (isJavascriptConstructorType(type) && !typeArgCount) { + return getSignaturesOfType(type, 0 /* Call */); + } + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); @@ -34082,6 +34542,9 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } + else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere @@ -34416,7 +34879,8 @@ var ts; } /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ function isThislessTypeParameter(node) { - return !node.constraint || isThislessType(node.constraint); + var constraint = ts.getEffectiveConstraintOfTypeParameter(node); + return !constraint || isThislessType(constraint); } /** * A variable-like declaration is free of this references if it has a type annotation @@ -34514,6 +34978,11 @@ var ts; && ts.isEntityNameExpression(node.expression) && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } /** * Indicates whether a declaration has a late-bindable dynamic name. */ @@ -34951,7 +35420,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_4 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -34974,7 +35443,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_4(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35078,7 +35547,7 @@ var ts; // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { var prop = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), /*_index*/ undefined, prop); + addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); @@ -35096,7 +35565,7 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - function addMemberForKeyType(t, _index, origin) { + function addMemberForKeyType(t) { // 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. @@ -35118,9 +35587,9 @@ var ts; prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : propType; - if (origin) { - prop.syntheticOrigin = origin; - prop.declarations = origin.declarations; + if (modifiersProp) { + prop.syntheticOrigin = modifiersProp; + prop.declarations = modifiersProp.declarations; } prop.nameType = t; members.set(propName, prop); @@ -35148,7 +35617,7 @@ var ts; errorType); } function getConstraintDeclarationForMappedType(type) { - return type.declaration.typeParameter.constraint; + return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 @@ -35276,11 +35745,7 @@ var ts; return obj.properties.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - if (expected && typeIsLiteralType(expected)) { - var actual = getTypeOfNode(property); - return !!actual && !isTypeIdenticalTo(actual, expected); - } - return false; + return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -35389,20 +35854,12 @@ var ts; } return undefined; } - function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { + function getBaseConstraintOfType(type) { if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } - } - } - function getBaseConstraintOfType(type) { - var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); - if (!constraint && type.flags & 1048576 /* Index */) { - return keyofConstraintType; + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return constraint; + return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -35420,23 +35877,24 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var circular; - if (!type.resolvedBaseConstraint) { - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + var result = computeBaseConstraint(getSimplifiedType(t)); + if (!popTypeResolution()) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; } - return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { - circular = true; - return undefined; - } - var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { - circular = true; - return undefined; - } - return result; + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { if (t.flags & 65536 /* TypeParameter */) { @@ -35449,8 +35907,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_3 = types_4[_i]; - var baseType = getBaseConstraint(type_3); + var type_2 = types_4[_i]; + var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); } @@ -35545,6 +36003,7 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; + var indexTypes; var isUnion = containingType.flags & 262144 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols @@ -35570,14 +36029,21 @@ var ts; } } else if (isUnion) { - checkFlags |= 16 /* Partial */; + var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); + if (index) { + checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, index.type); + } + else { + checkFlags |= 16 /* Partial */; + } } } } if (!props) { return undefined; } - if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } var declarations; @@ -35609,6 +36075,7 @@ var ts; } propTypes.push(type); } + ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && commonValueDeclaration) { @@ -35779,17 +36246,6 @@ var ts; var isBracketed = node.isBracketed, typeExpression = node.typeExpression; return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; } - function createTypePredicateFromTypePredicateNode(node) { - var parameterName = node.parameterName; - var type = getTypeFromTypeNode(node.type); - if (parameterName.kind === 71 /* Identifier */) { - return createIdentifierTypePredicate(parameterName && parameterName.escapedText, // TODO: GH#18217 - parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); - } - else { - return createThisTypePredicate(type); - } - } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; } @@ -35865,7 +36321,7 @@ var ts; var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } - if (i === 0 && paramSymbol.escapedName === "this") { + if (i === 0 && paramSymbol.escapedName === "this" /* This */) { hasThisParameter = true; thisParameter = param.symbol; } @@ -35899,9 +36355,9 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -35929,26 +36385,14 @@ var ts; parameters.push(syntheticArgsSymbol); return true; } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 - } - else if (classType) { - return classType; - } - var typeNode = ts.getEffectiveReturnTypeNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); - } - // TypeScript 1.0 spec (April 2014): - // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } + function getSignatureOfTypeTag(node) { + var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); + return signature && getErasedSignature(signature); + } + function getReturnTypeOfTypeTag(node) { + var signature = getSignatureOfTypeTag(node); + return signature && getReturnTypeOfSignature(signature); } function containsArgumentsReference(declaration) { var links = getNodeLinks(declaration); @@ -36028,52 +36472,105 @@ var ts; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + var jsdocPredicate = void 0; + if (!type && ts.isInJavaScriptFile(signature.declaration)) { + var jsdocSignature = getSignatureOfTypeTag(signature.declaration); + if (jsdocSignature && signature !== jsdocSignature) { + jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); + } + } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type) : - noTypePredicate; + createTypePredicateFromTypePredicateNode(type, signature.declaration) : + jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } + function createTypePredicateFromTypePredicateNode(node, func) { + var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); + if (parameterName.kind === 71 /* Identifier */) { + return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + } + else { + return createThisTypePredicate(type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + return -1; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } + var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : + signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : + getReturnTypeFromAnnotation(signature.declaration) || + (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + if (signature.declaration) { + var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration); + if (typeNode) { + error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself); } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + else if (noImplicitAny) { + var declaration = signature.declaration; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + type = anyType; } signature.resolvedReturnType = type; } return signature.resolvedReturnType; } + function getReturnTypeFromAnnotation(declaration) { + if (declaration.kind === 155 /* Constructor */) { + return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); + } + if (ts.isJSDocConstructSignature(declaration)) { + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return jsDocType; + } + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + if (setterType) { + return setterType; + } + } + return getReturnTypeOfTypeTag(declaration); + } function isResolvingReturnTypeOfSignature(signature) { return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */) || anyType; + return type && getIndexTypeOfType(type, 1 /* Number */); } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36173,7 +36670,7 @@ var ts; } function getConstraintDeclaration(type) { var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); - return decl && decl.constraint; + return decl && ts.getEffectiveConstraintOfTypeParameter(decl); } function getInferredTypeParameterConstraint(typeParameter) { var inferences; @@ -36219,6 +36716,7 @@ var ts; } return inferences && getIntersectionType(inferences); } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { if (typeParameter.target) { @@ -36234,7 +36732,9 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */).parent); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */); + var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; + return host && getSymbolOfNode(host); } function getTypeListId(types) { var result = ""; @@ -36424,6 +36924,10 @@ var ts; // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); } + var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag && enumTag.typeExpression) { + return getTypeFromTypeNode(enumTag.typeExpression); + } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -36473,7 +36977,7 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 162 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && (node.kind === 162 /* TypeReference */ || node.kind === 181 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -36564,7 +37068,7 @@ var ts; // The expression is processed as an identifier expression (section 4.3) // or property access expression(section 4.10), // the widened type(section 3.9) of which becomes the result. - links.resolvedType = getWidenedType(checkExpression(node.exprName)); + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); } return links.resolvedType; } @@ -36683,6 +37187,9 @@ var ts; function createArrayType(elementType) { return createTypeFromGenericGlobalType(globalArrayType, [elementType]); } + function createReadonlyArrayType(elementType) { + return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -36781,6 +37288,14 @@ var ts; function containsType(types, type) { return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } + function insertType(types, type) { + var index = ts.binarySearch(types, type, getTypeId, ts.compareValues); + if (index < 0) { + types.splice(~index, 0, type); + return true; + } + return false; + } // Return true if the given intersection type contains // more than one unit type or, // an object type and a nullable type (null or undefined), or @@ -36944,7 +37459,7 @@ var ts; includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, includes & 16749629 /* NotUnit */ ? 0 : 67108864 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 16748579 /* NotPrimitiveUnion */ ? 0 : 67108864 /* UnionOfPrimitiveTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -37059,29 +37574,65 @@ var ts; } } } - // When intersecting unions of unit types we can simply intersect based on type identity. - // Here we remove all unions of unit types from the given list and replace them with a - // a single union containing an intersection of the unit types. - function intersectUnionsOfUnitTypes(types) { - var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfUnitTypes */) !== 0; }); - var unionType = types[unionIndex]; - var intersection = unionType.types; - var i = types.length - 1; - var _loop_6 = function () { + // Check that the given type has a match in every union. A given type is matched by + // an identical type, and a literal type is additionally matched by its corresponding + // primitive type. + function eachUnionContains(unionTypes, type) { + for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) { + var u = unionTypes_1[_i]; + if (!containsType(u.types, type)) { + var primitive = type.flags & 64 /* StringLiteral */ ? stringType : + type.flags & 128 /* NumberLiteral */ ? numberType : + type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : + undefined; + if (!primitive || !containsType(u.types, primitive)) { + return false; + } + } + } + return true; + } + // If the given list of types contains more than one union of primitive types, replace the + // first with a union containing an intersection of those primitive types, then remove the + // other unions and return true. Otherwise, do nothing and return false. + function intersectUnionsOfPrimitiveTypes(types) { + var unionTypes; + var index = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfPrimitiveTypes */) !== 0; }); + var i = index + 1; + // Remove all but the first union of primitive types and collect them in + // the unionTypes array. + while (i < types.length) { var t = types[i]; - if (t.flags & 67108864 /* UnionOfUnitTypes */) { - intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + if (t.flags & 67108864 /* UnionOfPrimitiveTypes */) { + (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } - i--; - }; - while (i > unionIndex) { - _loop_6(); + else { + i++; + } } - if (intersection === unionType.types) { + // Return false if there was only one union of primitive types + if (!unionTypes) { return false; } - types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 67108864 /* UnionOfUnitTypes */); + // We have more than one union of primitive types, now intersect them. For each + // type in each union we check if the type is matched in every union and if so + // we include it in the result. + var checked = []; + var result = []; + for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) { + var u = unionTypes_2[_i]; + for (var _a = 0, _b = u.types; _a < _b.length; _a++) { + var t = _b[_a]; + if (insertType(checked, t)) { + if (eachUnionContains(unionTypes, t)) { + insertType(result, t); + } + } + } + } + // Finally replace the first union with the result + types[index] = getUnionTypeFromSortedList(result, 67108864 /* UnionOfPrimitiveTypes */); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -37121,7 +37672,7 @@ var ts; return typeSet[0]; } if (includes & 262144 /* Union */) { - if (includes & 67108864 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + if (includes & 67108864 /* UnionOfPrimitiveTypes */ && intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -37232,6 +37783,33 @@ var ts; type.indexType = indexType; return type; } + /** + * Returns if a type is or consists of a JSLiteral object type + * In addition to objects which are directly literals, + * * unions where every element is a jsliteral + * * intersections where at least one element is a jsliteral + * * and instantiable types constrained to a jsliteral + * Should all count as literals and not print errors on access or assignment of possibly existing properties. + * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference). + */ + function isJSLiteralType(type) { + if (noImplicitAny) { + return false; // Flag is meaningless under `noImplicitAny` mode + } + if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + return true; + } + if (type.flags & 262144 /* Union */) { + return ts.every(type.types, isJSLiteralType); + } + if (type.flags & 524288 /* Intersection */) { + return ts.some(type.types, isJSLiteralType); + } + if (type.flags & 15794176 /* Instantiable */) { + return isJSLiteralType(getResolvedBaseConstraint(type)); + } + return false; + } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : @@ -37251,7 +37829,8 @@ var ts; getNodeLinks(accessNode).resolvedSymbol = prop; } } - return getTypeOfSymbol(prop); + var propType = getTypeOfSymbol(prop); + return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; } if (isTupleType(objectType)) { var restType = getRestTypeOfTupleType(objectType); @@ -37261,7 +37840,7 @@ var ts; } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { - if (isTypeAny(objectType)) { + if (objectType.flags & (1 /* Any */ | 32768 /* Never */)) { return objectType; } var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || @@ -37280,9 +37859,15 @@ var ts; if (indexType.flags & 32768 /* Never */) { return neverType; } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1 /* Number */)) { + if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { + error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); + } + else if (getIndexTypeOfType(objectType, 1 /* Number */)) { error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); } else { @@ -37300,6 +37885,9 @@ var ts; return anyType; } } + if (isJSLiteralType(objectType)) { + return anyType; + } if (accessNode) { var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { @@ -37386,7 +37974,7 @@ var ts; return type.simplified = substituteIndexedMappedType(objectType, type); } if (objectType.flags & 65536 /* TypeParameter */) { - var constraint = getConstraintFromTypeParameter(objectType); + var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { return type.simplified = substituteIndexedMappedType(constraint, type); } @@ -37613,19 +38201,17 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var argumentType = getTypeFromTypeNode(node.argument); - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type - var moduleName = argumentType.value; - var innerModuleSymbol = resolveExternalModule(node, moduleName, ts.Diagnostics.Cannot_find_module_0, node, /*isForAugmentation*/ false); + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var moduleSymbol_1 = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); if (!ts.nodeIsMissing(node.qualifier)) { var nameStack = getIdentifierChain(node.qualifier); - var currentNamespace = moduleSymbol_1; + var currentNamespace = moduleSymbol; var current = void 0; while (current = nameStack.shift()) { var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; @@ -37641,14 +38227,14 @@ var ts; resolveImportSymbolType(node, links, currentNamespace, targetMeaning); } else { - if (moduleSymbol_1.flags & targetMeaning) { - resolveImportSymbolType(node, links, moduleSymbol_1, targetMeaning); + if (moduleSymbol.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { var errorMessage = targetMeaning === 67216319 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; - error(node, errorMessage, moduleName); + error(node, errorMessage, node.argument.literal.text); links.resolvedSymbol = unknownSymbol; links.resolvedType = errorType; } @@ -37734,20 +38320,16 @@ var ts; } for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { var rightProp = _a[_i]; - // we approximate own properties as non-methods plus methods that are inside the object literal - var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */); if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { skippedPrivateMembers.set(rightProp.escapedName, true); } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + else if (isSpreadableProperty(rightProp)) { members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { var leftProp = _c[_b]; - if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) - || skippedPrivateMembers.has(leftProp.escapedName) - || isClassMethod(leftProp)) { + if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) { continue; } if (members.has(leftProp.escapedName)) { @@ -37774,6 +38356,12 @@ var ts; spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } + /** We approximate own properties as non-methods plus methods that are inside the object literal */ + function isSpreadableProperty(prop) { + return prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */) + ? !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }) + : !(prop.flags & 65536 /* SetAccessor */); // Setter without getter is not spreadable + } function getNonReadonlySymbol(prop) { if (!isReadonlySymbol(prop)) { return prop; @@ -37792,9 +38380,6 @@ var ts; } return index; } - function isClassMethod(prop) { - return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } function createLiteralType(flags, value, symbol) { var type = createType(flags); type.symbol = symbol; @@ -37954,7 +38539,7 @@ var ts; case 71 /* Identifier */: case 146 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: return errorType; } @@ -38130,7 +38715,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavaScriptConstructor(declaration_1)) { + if (isJavascriptConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38190,11 +38775,16 @@ var ts; } } 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 - // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated - // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for - // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a - // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // operation depends on T as follows: + // * If T is a primitive type no mapping is performed and the result is simply T. + // * If T is a union type we distribute the mapped type over the union. + // * If T is an array we map to an array where the element type has been transformed. + // * If T is a tuple we map to a tuple where the element types have been transformed. + // * Otherwise we map to an object type where the type of each property has been transformed. + // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | + // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce + // { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & 1048576 /* Index */) { var typeVariable_1 = constraintType.type; @@ -38203,7 +38793,11 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); + var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); } return t; }); @@ -38215,6 +38809,25 @@ var ts; function isMappableType(type) { return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); } + function instantiateMappedTupleType(tupleType, mappedType, mapper) { + var minLength = tupleType.target.minLength; + var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { + return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper); + }); + var modifiers = getMappedTypeModifiers(mappedType); + var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : + modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : + minLength; + return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + } + function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { + var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); + var modifiers = getMappedTypeModifiers(type); + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : + propType; + } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { @@ -38366,6 +38979,9 @@ var ts; return true; } } + return hasContextSensitiveReturnExpression(node); + } + function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. var body = node.body; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); @@ -38377,7 +38993,7 @@ var ts; function getTypeWithoutSignatures(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { + if (resolved.constructSignatures.length || resolved.callSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; @@ -38517,8 +39133,8 @@ var ts; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } - if (!issuedElaboration && (ts.length(targetProp && targetProp.declarations) || ts.length(target.symbol && target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); } } reportedError = true; @@ -38667,9 +39283,9 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceRestTypeParameter = getRestTypeParameter(source); - var targetRestTypeParameter = sourceRestTypeParameter ? getRestTypeParameter(target) : undefined; - if (sourceRestTypeParameter && !(targetRestTypeParameter && sourceCount === targetCount)) { + var sourceGenericRestType = getGenericRestType(source); + var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; + if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -38695,8 +39311,8 @@ var ts; var paramCount = Math.max(sourceCount, targetCount); var lastIndex = paramCount - 1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceRestTypeParameter || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetRestTypeParameter || getTypeAtPosition(target, i); + var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); + var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -38722,11 +39338,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? + getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? + getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39231,6 +39849,9 @@ var ts; return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { + if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny + } if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && @@ -39241,7 +39862,7 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_7 = function (prop) { + var _loop_5 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -39280,9 +39901,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_3 = _loop_7(prop); - if (typeof state_3 === "object") - return state_3.value; + var state_2 = _loop_5(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -39314,7 +39935,8 @@ var ts; } if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || - findMatchingTypeReferenceOrTypeAliasReference(source, target); + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39336,6 +39958,11 @@ var ts; }); } } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -39935,8 +40562,12 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); + var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); + var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? + 0 /* Call */ : kind); if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) { // An abstract constructor type is not assignable to a non-abstract constructor type @@ -40186,7 +40817,7 @@ var ts; return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 65536 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); @@ -40448,6 +41079,9 @@ var ts; function isArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } + function isReadonlyArrayType(type) { + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; + } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray @@ -40630,7 +41264,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; - regularNew.objectFlags |= 128 /* ObjectLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); type.regularType = regularNew; return regularNew; } @@ -40708,7 +41342,9 @@ var ts; } var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); - return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Retain js literal flag through widening + return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); @@ -40840,13 +41476,13 @@ var ts; sourceHasRest ? targetCount : targetHasRest ? sourceCount : Math.min(sourceCount, targetCount); - var targetRestTypeVariable = getRestTypeParameter(target); - var paramCount = targetRestTypeVariable ? Math.min(targetCount - 1, maxCount) : maxCount; + var targetGenericRestType = getGenericRestType(target); + var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetRestTypeVariable) { - callback(getRestTypeAtPosition(source, paramCount), targetRestTypeVariable); + if (targetGenericRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -40958,6 +41594,22 @@ var ts; return undefined; } } + // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been + // applied to the element type(s). + if (isArrayType(source)) { + return createArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isReadonlyArrayType(source)) { + return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target)); + } + if (isTupleType(source)) { + var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target); }); + var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? + getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + } + // For all other object types we infer a new object type where the reverse mapping has been + // applied to the type of each property. var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; @@ -41522,7 +42174,7 @@ var ts; case 71 /* Identifier */: return ts.idText(name); case 147 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return name.text; @@ -41546,8 +42198,9 @@ var ts; case 97 /* SuperKeyword */: return target.kind === 97 /* SuperKeyword */; case 187 /* PropertyAccessExpression */: - return target.kind === 187 /* PropertyAccessExpression */ && - source.name.escapedText === target.name.escapedText && + case 188 /* ElementAccessExpression */: + return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); case 184 /* BindingElement */: if (target.kind !== 187 /* PropertyAccessExpression */) @@ -41565,6 +42218,11 @@ var ts; } return false; } + function getAccessedPropertyName(access) { + return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : + undefined; + } function containsMatchingReference(source, target) { while (source.kind === 187 /* PropertyAccessExpression */) { source = source.expression; @@ -41644,18 +42302,6 @@ var ts; } return flow.id; } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 262144 /* Union */)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -41664,7 +42310,7 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); if (!(reducedType.flags & 32768 /* Never */)) { return reducedType; } @@ -41920,7 +42566,7 @@ var ts; if (type.flags & 262144 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfUnitTypes */); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfPrimitiveTypes */); } return f(type) ? type : neverType; } @@ -42162,7 +42808,10 @@ var ts; 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 !== 187 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + if (container && container !== flowContainer && + reference.kind !== 187 /* PropertyAccessExpression */ && + reference.kind !== 188 /* ElementAccessExpression */ && + reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -42391,13 +43040,22 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 187 /* PropertyAccessExpression */ && - computedType.flags & 262144 /* Union */ && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(computedType, expr.name.escapedText); + if (!(computedType.flags & 262144 /* Union */) || + expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { + return false; + } + var access = expr; + var name = getAccessedPropertyName(access); + if (!name) { + return false; + } + return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.escapedText; + function narrowTypeByDiscriminant(type, access, narrowType) { + var propName = getAccessedPropertyName(access); + if (!propName) { + return type; + } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); @@ -42681,6 +43339,7 @@ var ts; case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); case 189 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); @@ -42897,6 +43556,7 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isModuleExports = symbol.flags & 134217728 /* ModuleExports */; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -42908,7 +43568,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || node.parent.kind === 211 /* NonNullExpression */ || @@ -43071,15 +43731,14 @@ var ts; // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); - var needToCaptureLexicalThis = false; + var capturedByArrowFunction = false; if (container.kind === 155 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. if (container.kind === 195 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); - // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); + capturedByArrowFunction = true; } switch (container.kind) { case 242 /* ModuleDeclaration */: @@ -43107,13 +43766,16 @@ var ts; error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } - if (needToCaptureLexicalThis) { + // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope. + if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { captureLexicalThis(node, container); } var type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + error(node, capturedByArrowFunction && container.kind === 277 /* SourceFile */ ? + ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); } return type || anyType; } @@ -43122,8 +43784,8 @@ var ts; if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. Check if it's the RHS - // of a x.prototype.y = function [name]() { .... } + // If this is a function in a JS file, it might be a class method. + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } if (container.kind === 194 /* FunctionExpression */ && container.parent.kind === 202 /* BinaryExpression */ && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { @@ -43137,6 +43799,17 @@ var ts; return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); } } + // Check if it's a constructor definition, can be either a variable decl or function decl + // i.e. + // * /** @constructor */ function [name]() { ... } + // * /** @constructor */ var x = function() { ... } + else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + ts.getJSDocClassTag(container)) { + var classType = getJavascriptClassType(container.symbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } + } var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); if (thisType) { return getFlowTypeOfReference(node, thisType); @@ -43160,7 +43833,7 @@ var ts; var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && - jsDocFunctionType.parameters[0].name.escapedText === "this") { + jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } @@ -43449,20 +44122,10 @@ var ts; } var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameter = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameter ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - // If last parameter is contextually rest parameter get its type - if (funcHasRestParameter && indexOfParameter === len) { - return getRestTypeAtPosition(contextualSignature, indexOfParameter); - } + var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0); + return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ? + getRestTypeAtPosition(contextualSignature, index) : + tryGetTypeAtPosition(contextualSignature, index); } } // In a variable, parameter or property declaration with a type annotation, @@ -43548,10 +44211,9 @@ var ts; function getContextualReturnType(functionDecl) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.kind === 155 /* Constructor */ || - ts.getEffectiveReturnTypeNode(functionDecl) || - isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + var returnType = getReturnTypeFromAnnotation(functionDecl); + if (returnType) { + return returnType; } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature @@ -43600,22 +44262,39 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments to avoid circularity. + // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function isContextSensitiveAssignment(binaryExpression) { var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); switch (kind) { case 0 /* None */: return true; case 5 /* Property */: - // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. - // See `bindStaticPropertyAssignment` in `binder.ts`. - return !binaryExpression.left.symbol; case 1 /* ExportsProperty */: - case 2 /* ModuleExports */: + case 6 /* Prototype */: case 3 /* PrototypeProperty */: + // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. + // See `bindStaticPropertyAssignment` in `binder.ts`. + if (!binaryExpression.left.symbol) { + return true; + } + else { + var decl = binaryExpression.left.symbol.valueDeclaration; + if (!decl) { + return false; + } + if (ts.isInJavaScriptFile(decl)) { + return !!ts.getJSDocTypeTag(decl); + } + else if (ts.isIdentifier(binaryExpression.left.expression)) { + var id = binaryExpression.left.expression; + var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); + return !ts.isFunctionSymbol(parentSymbol); + } + return true; + } case 4 /* ThisProperty */: - case 6 /* Prototype */: - return false; + case 2 /* ModuleExports */: + return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); default: return ts.Debug.assertNever(kind); } @@ -44030,16 +44709,11 @@ var ts; // union type of return types from these signatures function getContextualSignature(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type; - if (ts.isInJavaScriptFile(node)) { - var jsdoc = ts.getJSDocType(node); - if (jsdoc) { - type = getTypeFromTypeNode(jsdoc); - } - } - if (!type) { - type = getContextualTypeForFunctionLikeDeclaration(node); + var typeTagSignature = getSignatureOfTypeTag(node); + if (typeTagSignature) { + return typeTagSignature; } + var type = getContextualTypeForFunctionLikeDeclaration(node); if (!type) { return undefined; } @@ -44247,7 +44921,8 @@ var ts; var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); - var isJSObjectLiteral = !contextualType && isInJSFile; + var enumTag = ts.getJSDocEnumTag(node); + var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44271,6 +44946,9 @@ var ts; checkTypeAssignableTo(type, jsDocType, memberDecl); type = jsDocType; } + else if (enumTag && enumTag.typeExpression) { + checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); + } } typeFlags |= type.flags; var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? @@ -44380,12 +45058,15 @@ var ts; } return createObjectLiteralType(); function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); result.objectFlags |= 128 /* ObjectLiteral */; + if (isJSObjectLiteral) { + result.objectFlags |= 16384 /* JSLiteral */; + } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } @@ -44772,7 +45453,7 @@ var ts; var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); @@ -44808,7 +45489,7 @@ var ts; if (jsxStatelessElementType) { // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); var result = void 0; var allMatchingAttributesType = void 0; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { @@ -45116,6 +45797,10 @@ var ts; } } } + else if (targetType.flags & 4194304 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } return false; } /** @@ -45173,11 +45858,6 @@ var ts; return errorType; } } - // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized - // '.prototype' property as well as synthesized tuple index properties. - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 152 /* PropertyDeclaration */; - } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } @@ -45199,23 +45879,19 @@ var ts; * Check whether the requested property access is valid. * Returns true if node is a valid property access, and false otherwise. * @param node The node to be checked. - * @param left The left hand side of the property access (e.g.: the super in `super.foo`). - * @param type The type of left. - * @param prop The symbol for the right hand side of the property access. + * @param isSuper True if the access is from `super.`. + * @param type The type of the object whose property is being accessed. (Not the type of the property.) + * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, left, type, prop) { + function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 187 /* PropertyAccessExpression */ || node.kind === 235 /* VariableDeclaration */ ? - node.name : - node.kind === 181 /* ImportType */ ? - node : - node.right; + var errorNode = node.kind === 146 /* QualifiedName */ ? node.right : node.kind === 181 /* ImportType */ ? node : node.name; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or // instance member variable initializer where this references a derived class instance, @@ -45262,7 +45938,7 @@ var ts; } // Property is known to be protected at this point // All protected properties of a supertype are accessible in a super access - if (left.kind === 97 /* SuperKeyword */) { + if (isSuper) { return true; } // Find the first enclosing class that has the declaring classes of the protected constituents @@ -45281,7 +45957,7 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintFromTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { @@ -45302,10 +45978,7 @@ var ts; return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; } function symbolHasNonMethodDeclaration(symbol) { - return forEachProperty(symbol, function (prop) { - var propKind = getDeclarationKindFromSymbol(prop); - return propKind !== 154 /* MethodDeclaration */ && propKind !== 153 /* MethodSignature */; - }); + return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); @@ -45351,6 +46024,9 @@ var ts; if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { + if (isJSLiteralType(leftType)) { + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } @@ -45365,7 +46041,7 @@ var ts; checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); + checkPropertyAccessibility(node, left.kind === 97 /* SuperKeyword */, apparentType, prop); if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); @@ -45423,7 +46099,7 @@ var ts; diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_was_declared_here, declarationName)); + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializer(node) { @@ -45468,6 +46144,7 @@ var ts; } function reportNonexistentProperty(propNode, containingType) { var errorInfo; + var relatedInfo; if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; @@ -45477,32 +46154,44 @@ var ts; } } } - var promisedType = getPromisedTypeOfPromise(containingType); - if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); + if (typeHasStaticProperty(propNode.escapedText, containingType)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - 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), suggestion); + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - var suggestion_1 = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion_1 !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion_1); + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); + } + function typeHasStaticProperty(propName, containingType) { + var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); + return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); + } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { - var suggestion = getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); @@ -45512,10 +46201,17 @@ var ts; // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - return result && ts.symbolName(result); + return result; } - function getSuggestionForNonexistentModule(name, targetModule) { - var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); return suggestion && ts.symbolName(suggestion); } /** @@ -45559,15 +46255,15 @@ var ts; function isValidPropertyAccess(node, propertyName) { switch (node.kind) { case 187 /* PropertyAccessExpression */: - return isValidPropertyAccessWithType(node, node.expression, propertyName, getWidenedType(checkExpression(node.expression))); + return isValidPropertyAccessWithType(node, node.expression.kind === 97 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); case 146 /* QualifiedName */: - return isValidPropertyAccessWithType(node, node.left, propertyName, getWidenedType(checkExpression(node.left))); + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); case 181 /* ImportType */: - return isValidPropertyAccessWithType(node, node, propertyName, getTypeFromTypeNode(node)); + return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 181 /* ImportType */ ? node : node.expression, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind !== 181 /* ImportType */ && node.expression.kind === 97 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -45587,14 +46283,14 @@ var ts; inferTypes(context.inferences, actualThisType, signatureThisType); return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); } - function isValidPropertyAccessWithType(node, left, propertyName, type) { + function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { if (type === errorType || isTypeAny(type)) { return true; } var prop = getPropertyOfType(type, propertyName); - return prop ? checkPropertyAccessibility(node, left, type, prop) + return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -45790,7 +46486,6 @@ var ts; function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call - var typeArguments; // Type arguments (undefined if none) var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { @@ -45801,7 +46496,6 @@ var ts; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = node.typeArguments; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. @@ -45818,7 +46512,6 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { @@ -45830,12 +46523,8 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } - if (!hasCorrectTypeArgumentArity(signature, typeArguments)) { - return false; - } // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. if (spreadArgIndex >= 0) { return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); @@ -45939,8 +46628,8 @@ var ts; // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var restTypeParameter = getRestTypeParameter(signature); - var argCount = restTypeParameter ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var genericRestType = getGenericRestType(signature); + var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. @@ -45958,9 +46647,9 @@ var ts; inferTypes(context.inferences, argType, paramType); } } - if (restTypeParameter) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, restTypeParameter, context); - inferTypes(context.inferences, spreadType, restTypeParameter); + if (genericRestType) { + var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); + inferTypes(context.inferences, spreadType, genericRestType); } // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed @@ -46356,7 +47045,7 @@ var ts; node.kind === 157 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - var propertyType = getTypeOfNode(node); // TODO: GH#18217 + var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); @@ -46422,18 +47111,54 @@ var ts; return arg; } } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + min = Math.min(min, minCount); + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; var max = -Infinity; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } var paramCount = min === max ? min : min + "-" + max; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; var isDecorator = node.kind === 150 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -46505,11 +47230,12 @@ var ts; // foo(0); // var candidateForArgumentError; + var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -46545,73 +47271,30 @@ var ts; // an error, we don't need to exclude any arguments, although it would cause no harm to do so. checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { + else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { - var min_1 = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; - min_1 = Math.min(min_1, getMinArgumentCount(sig)); - max = Math.max(max, getParameterCount(sig)); - } - var hasRestParameter_1 = ts.some(signatures, hasEffectiveRestParameter); - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - var paramCount = hasRestParameter_1 ? min_1 : - min_1 < max ? min_1 + "-" + max : - min_1; - var argCount = args.length; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - ts.Diagnostics.Expected_0_arguments_but_got_1; - diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + diagnostics.add(getArgumentArityError(node, signatures, args)); } else if (fallbackError) { diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } - // No signature was applicable. We have already reported the errors for the invalid signature. - // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. - // Pick the longest signature. This way we can get a contextual type for cases like: - // declare function f(a: { xa: number; xb: number; }, b: number); - // f({ | - // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: - // declare function f(k: keyof T); - // f(" - if (!produceDiagnostics) { - ts.Debug.assert(candidates.length > 0); // Else would have exited above. - var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); - var candidate = candidates[bestIndex]; - var typeParameters = candidate.typeParameters; - if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); // TODO: GH#18217 - while (typeArguments_1.length > typeParameters.length) { - typeArguments_1.pop(); - } - while (typeArguments_1.length < typeParameters.length) { - typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); - } - var instantiated = createSignatureInstantiation(candidate, typeArguments_1); - candidates[bestIndex] = instantiated; - return instantiated; - } - return candidate; - } - return resolveErrorCall(node); + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -46622,7 +47305,7 @@ var ts; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; @@ -46648,6 +47331,12 @@ var ts; } var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = candidate; + break; + } } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; @@ -46669,6 +47358,87 @@ var ts; return undefined; } } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_6 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_6(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArguments = typeArgumentNodes.map(getTypeOfNode); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments); + candidates[bestIndex] = instantiated; + return instantiated; + } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; var maxParams = -1; @@ -46685,11 +47455,14 @@ var ts; } return maxParamsIndex; } - function resolveCallExpression(node, candidatesOutArray) { + function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { - ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + checkExpression(arg); // Still visit arguments so they get marked for visibility, etc + } return anySignature; } if (superType !== errorType) { @@ -46698,7 +47471,7 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); + return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); } } return resolveUntypedCall(node); @@ -46741,7 +47514,12 @@ var ts; } return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + // If the function is explicitly marked with `@class`, then it must be constructed. + if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * TS 1.0 spec: 4.12 @@ -46753,7 +47531,7 @@ var ts; return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } - function resolveNewExpression(node, candidatesOutArray) { + function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { @@ -46801,7 +47579,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray); + return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -46809,8 +47587,8 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } if (getThisTypeOfSignature(signature) === voidType) { @@ -46821,6 +47599,38 @@ var ts; invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 524288 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } function isConstructorAccessible(node, signature) { if (!signature || !signature.declaration) { return true; @@ -46836,16 +47646,10 @@ var ts; // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); - if (containingClass) { + if (containingClass && modifiers & 16 /* Protected */) { var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; } } if (modifiers & 8 /* Private */) { @@ -46877,7 +47681,7 @@ var ts; addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { + function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); if (apparentType === errorType) { @@ -46893,7 +47697,7 @@ var ts; invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -46918,7 +47722,7 @@ var ts; /** * Resolves a decorator as if it were a call expression. */ - function resolveDecorator(node, candidatesOutArray) { + function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); if (apparentType === errorType) { @@ -46943,7 +47747,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -46967,30 +47771,30 @@ var ts; * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; * the function will fill it up with appropriate candidate signatures */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); } return undefined; } - function resolveSignature(node, candidatesOutArray) { + function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { switch (node.kind) { case 189 /* CallExpression */: - return resolveCallExpression(node, candidatesOutArray); + return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); case 190 /* NewExpression */: - return resolveNewExpression(node, candidatesOutArray); + return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); case 191 /* TaggedTemplateExpression */: - return resolveTaggedTemplateExpression(node, candidatesOutArray); + return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); case 150 /* Decorator */: - return resolveDecorator(node, candidatesOutArray); + return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); case 260 /* JsxOpeningElement */: case 259 /* JsxSelfClosingElement */: // This code-path is called by language service var exprTypes = checkExpression(node.tagName); return forEachType(exprTypes, function (exprType) { - var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); if (sfcResult && sfcResult !== unknownSignature) { return sfcResult; } @@ -47010,7 +47814,8 @@ var ts; * the function will fill it up with appropriate candidate signatures * @return a signature of the call-like expression or undefined if one can't be found */ - function getResolvedSignature(node, candidatesOutArray) { + function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { + if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } var links = getNodeLinks(node); // If getResolvedSignature has already been called, we will have cached the resolvedSignature. // However, it is possible that either candidatesOutArray was not passed in the first time, @@ -47021,7 +47826,7 @@ var ts; return cached; } links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); + var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); // If signature resolution originated in control flow type analysis (for example to compute the // assigned type in a flow assignment) we don't cache the result as it may be based on temporary // types from the control flow analysis. @@ -47032,7 +47837,7 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavaScriptConstructor(node) { + function isJavascriptConstructor(node) { if (node && ts.isInJavaScriptFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) @@ -47045,14 +47850,21 @@ var ts; } return false; } - function getJavaScriptClassType(symbol) { + function isJavascriptConstructorType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + } + return false; + } + function getJavascriptClassType(symbol) { var inferred; - if (isJavaScriptConstructor(symbol.valueDeclaration)) { + if (isJavascriptConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47125,7 +47937,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavaScriptClassType(funcSymbol); + var type = funcSymbol && getJavascriptClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47151,7 +47963,8 @@ var ts; if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { - jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); + jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; } } } @@ -47268,7 +48081,7 @@ var ts; if (produceDiagnostics && targetType !== errorType) { var widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); } } return targetType; @@ -47335,6 +48148,9 @@ var ts; return restParameter.escapedName; } function getTypeAtPosition(signature, pos) { + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); @@ -47345,22 +48161,19 @@ var ts; if (pos - paramCount < getLengthOfTupleType(restType)) { return restType.typeArguments[pos - paramCount]; } - var tupleRestType = getRestTypeOfTupleType(restType); - if (tupleRestType) { - return tupleRestType; - } + return getRestTypeOfTupleType(restType); } - return getIndexTypeOfType(restType, 1 /* Number */) || anyType; + return getIndexTypeOfType(restType, 1 /* Number */); } - return anyType; + return undefined; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); var hasRest = hasEffectiveRestParameter(source); if (hasRest && pos === paramCount - 1) { - var restTypeVariable = getRestTypeParameter(source); - if (restTypeVariable) { - return restTypeVariable; + var genericRestType = getGenericRestType(source); + if (genericRestType) { + return genericRestType; } } var start = hasRest ? Math.min(pos, paramCount - 1) : pos; @@ -47406,10 +48219,10 @@ var ts; } return signature.minArgumentCount; } - function getRestTypeParameter(signature) { + function getGenericRestType(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 65536 /* TypeParameter */) { + if (restType.flags & 15794176 /* Instantiable */) { return restType; } } @@ -47677,7 +48490,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -47708,7 +48521,7 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 3 /* AnyOrUnknown */ | 4096 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 4096 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. @@ -47749,6 +48562,16 @@ var ts; ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage + if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { + var links_1 = getNodeLinks(node); + if (links_1.contextFreeType) { + return links_1.contextFreeType; + } + var returnType = getReturnTypeFromBody(node, checkMode); + var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + } return anyFunctionType; } // Grammar checking @@ -47780,7 +48603,7 @@ var ts; contextualSignature : instantiateSignature(contextualSignature, contextualMapper); assignContextualParameterTypes(signature, instantiatedContextualSignature); } - if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, checkMode); if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; @@ -47793,20 +48616,21 @@ var ts; } return type; } + function getReturnOrPromisedType(node, functionFlags) { + var type = getReturnTypeFromAnnotation(node); + return type && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) ? + getAwaitedType(type) || errorType : type; + } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - var returnOrPromisedType = returnTypeNode && - ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : // Async function - getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { - if (!returnTypeNode) { + if (!ts.getEffectiveReturnTypeNode(node)) { // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors // we need. An example is the noImplicitAny errors resulting from widening the return expression // of a function. Because checking of function expression bodies is deferred, there was never an @@ -47870,7 +48694,7 @@ var ts; // If func.parent is a class and symbol is a (readonly) property of that class, or // if func is a constructor and symbol is a (readonly) parameter property declared in it, // then symbol is writeable here. - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + return !symbol.valueDeclaration || !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -47956,6 +48780,7 @@ var ts; } return numberType; case 51 /* ExclamationToken */: + checkTruthinessExpression(node.operand); var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); return facts === 1048576 /* Truthy */ ? falseType : facts === 2097152 /* Falsy */ ? trueType : @@ -48065,19 +48890,20 @@ var ts; } return booleanType; } - function checkObjectLiteralAssignment(node, sourceType) { + function checkObjectLiteralAssignment(node, sourceType, rightIsThis) { var properties = node.properties; if (strictNullChecks && properties.length === 0) { return checkNonNullType(sourceType, node); } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis); } return sourceType; } /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties, rightIsThis) { + if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { var name = property.name; if (name.kind === 147 /* ComputedPropertyName */) { @@ -48086,20 +48912,10 @@ var ts; if (isComputedNonLiteralName(name)) { return undefined; } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || - getIndexTypeOfType(objectLiteralType, 0 /* String */); + var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); if (type) { - if (property.kind === 274 /* ShorthandPropertyAssignment */) { - return checkDestructuringAssignment(property, type); - } - else { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.initializer, type); - } + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.kind === 274 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); @@ -48123,6 +48939,23 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } + function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { + if (isTypeAny(objectLiteralType)) { + return objectLiteralType; + } + var type; + var text = ts.getTextOfPropertyName(name); + if (text) { // TODO: GH#26379 + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + type = getTypeOfSymbol(prop); + } + type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); + } + return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); + } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -48180,7 +49013,7 @@ var ts; } return undefined; } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; @@ -48203,7 +49036,7 @@ var ts; target = target.left; } if (target.kind === 186 /* ObjectLiteralExpression */) { - return checkObjectLiteralAssignment(target, sourceType); + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } if (target.kind === 185 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); @@ -48293,9 +49126,15 @@ var ts; function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 99 /* ThisKeyword */); + } + var leftType; + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + leftType = checkTruthinessExpression(left, checkMode); + } + else { + leftType = checkExpression(left, checkMode); } - var leftType = checkExpression(left, checkMode); var rightType = checkExpression(right, checkMode); switch (operator) { case 39 /* AsteriskToken */: @@ -48417,7 +49256,7 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.getSpecialPropertyAssignmentKind(left.parent); + var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; checkSpecialAssignment(special, right); if (isJSSpecialPropertyAssignment(special)) { return leftType; @@ -48497,8 +49336,9 @@ var ts; } function isJSSpecialPropertyAssignment(special) { switch (special) { - case 1 /* ExportsProperty */: case 2 /* ModuleExports */: + return true; + case 1 /* ExportsProperty */: case 5 /* Property */: case 6 /* Prototype */: case 3 /* PrototypeProperty */: @@ -48582,16 +49422,16 @@ var ts; // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. - var returnType = ts.getEffectiveReturnTypeNode(func); + var returnType = getReturnTypeFromAnnotation(func); if (returnType) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; + var signatureElementType = getIteratedTypeOfGenerator(returnType, isAsync) || anyType; checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); } // Both yield and yield* expressions have type 'any' return anyType; } function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); + checkTruthinessExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -48604,7 +49444,7 @@ var ts; // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { - error(templateSpan.expression, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1, typeToString(esSymbolType), typeToString(stringType)); + error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String); } }); return stringType; @@ -48774,9 +49614,6 @@ var ts; node.contextualType = saveContextualType; return type; } - function checkExpresionNoReturn(node) { - checkExpression(node); - } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -48919,7 +49756,7 @@ var ts; checkSourceElement(node.default); var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); } if (!hasNonCircularTypeParameterDefault(typeParameter)) { error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); @@ -48959,6 +49796,9 @@ var ts; if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } + if (func.kind === 195 /* ArrowFunction */) { + error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); + } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. @@ -48966,17 +49806,6 @@ var ts; error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - } - return -1; - } function checkTypePredicate(node) { var parent = getTypePredicateParent(node); if (!parent) { @@ -49000,8 +49829,7 @@ var ts; } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), // TODO: GH#18217 - node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -49122,7 +49950,7 @@ var ts; } } else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node); + checkAsyncFunctionReturnType(node, returnTypeNode); } } if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { @@ -49577,7 +50405,10 @@ var ts; } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, keyofConstraintType, node.typeParameter.constraint); + checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); + } + function checkThisType(node) { + getTypeFromThisTypeNode(node); } function checkTypeOperator(node) { checkGrammarTypeOperatorNode(node); @@ -49591,6 +50422,7 @@ var ts; grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); + registerForUnusedIdentifiersCheck(node); } function checkImportType(node) { checkSourceElement(node.argument); @@ -49878,7 +50710,7 @@ var ts; case 239 /* InterfaceDeclaration */: case 240 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return 2 /* ExportType */; case 242 /* ModuleDeclaration */: @@ -50077,16 +50909,15 @@ var ts; * Checks the return type of an async function to ensure it is a compatible * Promise implementation. * - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. + * This checks that an async function has a valid Promise-compatible return type. + * An async function has a valid Promise-compatible return type if the resolved value + * of the return type has a construct signature that takes in an `initializer` function + * that in turn supplies a `resolve` function as one of its arguments and results in an + * object with a callable `then` signature. * * @param node The signature to check */ - function checkAsyncFunctionReturnType(node) { + function checkAsyncFunctionReturnType(node, returnTypeNode) { // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -50111,30 +50942,29 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); // TODO: GH#18217 var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { if (returnType === errorType) { - return errorType; + return; } var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return errorType; + return; } } else { // Always mark the type node as referenced if it points to a value markTypeNodeAsReferenced(returnTypeNode); if (returnType === errorType) { - return errorType; + return; } var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === undefined) { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return errorType; + return; } var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; @@ -50145,28 +50975,27 @@ var ts; else { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); } - return errorType; + return; } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return errorType; + return; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); - return errorType; + return; } } - // Get and return the awaited type of the return type. - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } /** Check a decorator */ function checkDecorator(node) { @@ -50197,7 +51026,7 @@ var ts; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); // TODO: GH#18217 + var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; @@ -50321,9 +51150,13 @@ var ts; } } break; - case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: + var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 154 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); @@ -50363,6 +51196,13 @@ var ts; } checkSourceElement(node.typeExpression); } + function checkJSDocTemplateTag(node) { + checkSourceElement(node.constraint); + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var tp = _a[_i]; + checkSourceElement(tp); + } + } function checkJSDocTypeTag(node) { checkSourceElement(node.typeExpression); } @@ -50457,14 +51297,11 @@ var ts; } var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function - var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ - ? checkAsyncFunctionReturnType(node) // Async function - : getTypeFromTypeNode(returnTypeNode)); // normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } - if (produceDiagnostics && !returnTypeNode) { + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { @@ -50477,6 +51314,13 @@ var ts; getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJavaScriptFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } } function registerForUnusedIdentifiersCheck(node) { // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. @@ -50531,6 +51375,7 @@ var ts; case 163 /* FunctionType */: case 164 /* ConstructorType */: case 240 /* TypeAliasDeclaration */: + case 174 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -50541,7 +51386,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(node, message, name)); + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; @@ -50561,14 +51406,14 @@ var ts; } var symbol = getSymbolOfNode(member); if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; case 155 /* 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 */)) { - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } } break; @@ -50585,16 +51430,45 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { + if (node.flags & 4194304 /* Ambient */ || node.kind !== 174 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) + return; + if (node.kind === 174 /* InferType */) { + var typeParameter = node.typeParameter; + if (isTypeParameterUnused(typeParameter)) { + addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name))); + } + } + else { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + var seenParentsWithEveryUnused = new ts.NodeSet(); for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var typeParameter = typeParameters_2[_i]; - if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol))); + if (!isTypeParameterUnused(typeParameter)) + continue; + var name = ts.idText(typeParameter.name); + var parent = typeParameter.parent; + if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (seenParentsWithEveryUnused.tryAdd(parent)) { + var range = ts.isJSDocTemplateTag(parent) + // Whole @template tag + ? ts.rangeOfNode(parent) + // Include the `<>` in the error message + : ts.rangeOfTypeParameters(parent.typeParameters); + var only = typeParameters.length === 1; + var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; + var arg0 = only ? name : undefined; + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); + } + } + else { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } } } + function isTypeParameterUnused(typeParameter) { + return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name); + } function addToGroup(map, key, value, getKey) { var keyString = String(getKey(key)); var group = map.get(keyString); @@ -50645,7 +51519,7 @@ var ts; var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); if (parameter && name) { if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { @@ -50662,7 +51536,7 @@ var ts; (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { - addDiagnostic(0 /* Local */, unuseds.length === 1 + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); } @@ -50681,29 +51555,29 @@ var ts; addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - addDiagnostic(kind, bindingElements.length === 1 - ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name)) : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); } } else { for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { var e = bindingElements_1[_i]; - addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name))); } } }); unusedVariables.forEach(function (_a) { var declarationList = _a[0], declarations = _a[1]; if (declarationList.declarations.length === declarations.length) { - addDiagnostic(0 /* Local */, declarations.length === 1 + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var decl = declarations_5[_i]; - addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); } } }); @@ -51006,10 +51880,13 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); + var nameText = ts.getTextOfPropertyName(name); + if (nameText) { + var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. + if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); + } } } } @@ -51130,7 +52007,7 @@ var ts; function checkIfStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.thenStatement); if (node.thenStatement.kind === 218 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); @@ -51141,14 +52018,21 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); checkSourceElement(node.statement); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); } function checkWhileStatement(node) { // Grammar checking checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); + checkTruthinessExpression(node.expression); checkSourceElement(node.statement); } + function checkTruthinessExpression(node, checkMode) { + var type = checkExpression(node, checkMode); + if (type.flags & 4096 /* Void */) { + error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } + return type; + } function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { @@ -51165,7 +52049,7 @@ var ts; } } if (node.condition) - checkExpression(node.condition); + checkTruthinessExpression(node.condition); if (node.incrementor) checkExpression(node.incrementor); checkSourceElement(node.statement); @@ -51569,10 +52453,6 @@ var ts; checkGrammarBreakOrContinueStatement(node); // TODO: Check that target label is valid } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 156 /* GetAccessor */ - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 157 /* SetAccessor */)) !== undefined; - } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function @@ -51612,7 +52492,7 @@ var ts; error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + else if (getReturnTypeFromAnnotation(func)) { if (functionFlags & 2 /* Async */) { // Async function var promisedType = getPromisedTypeOfPromise(returnType); var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -51921,8 +52801,9 @@ var ts; } // If the type parameter node does not have an identical constraint as the resolved // type parameter at this position, we report an error. - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); + var constraint = ts.getEffectiveConstraintOfTypeParameter(source); + var sourceConstraint = constraint && getTypeFromTypeNode(constraint); + var targetConstraint = getConstraintOfTypeParameter(target); if (sourceConstraint) { // relax check if later interface augmentation has no constraint if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { @@ -52018,8 +52899,9 @@ var ts; // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). + // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52062,7 +52944,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_7 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52081,7 +52963,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_7(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -52841,9 +53723,9 @@ var ts; } else { // export * from "foo" - var moduleSymbol_2 = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol_2 && hasExportAssignmentSymbol(moduleSymbol_2)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol_2)); + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + 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 && moduleKind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768 /* ExportStar */); @@ -52934,9 +53816,9 @@ var ts; } } // Checks for export * conflicts - var exports_2 = getExportsOfModule(moduleSymbol); - if (exports_2) { - exports_2.forEach(function (_a, id) { + var exports_1 = getExportsOfModule(moduleSymbol); + if (exports_1) { + exports_1.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -53036,6 +53918,8 @@ var ts; case 169 /* OptionalType */: case 170 /* RestType */: return checkSourceElement(node.type); + case 176 /* ThisType */: + return checkThisType(node); case 177 /* TypeOperator */: return checkTypeOperator(node); case 173 /* ConditionalType */: @@ -53046,12 +53930,14 @@ var ts; return checkImportType(node); case 293 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 301 /* JSDocTypedefTag */: + case 302 /* JSDocTypedefTag */: case 295 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 299 /* JSDocTypeTag */: + case 301 /* JSDocTemplateTag */: + return checkJSDocTemplateTag(node); + case 300 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 296 /* JSDocParameterTag */: + case 297 /* JSDocParameterTag */: return checkJSDocParameterTag(node); case 287 /* JSDocFunctionType */: checkSignatureDeclaration(node); @@ -53264,10 +54150,7 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1 /* TypeChecked */)) { - // If skipLibCheck is enabled, skip type checking if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip type checking if file contains a - // '/// ' directive. - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + if (ts.skipTypeChecking(node, compilerOptions)) { return; } // Grammar checking @@ -53281,8 +54164,8 @@ var ts; registerForUnusedIdentifiersCheck(node); } if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { - checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) { - if (unusedIsError(kind)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { diagnostics.add(diag); } }); @@ -53361,6 +54244,7 @@ var ts; var symbols = ts.createSymbolTable(); var isStatic = false; populateSymbols(); + symbols.delete("this" /* This */); // Not a symbol, a keyword return symbolsToArray(symbols); function populateSymbols() { while (location) { @@ -53583,10 +54467,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 296 /* JSDocParameterTag */) { + if (entityName.parent.kind === 297 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 300 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -53655,7 +54539,7 @@ var ts; grandParent.kind === 182 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; } @@ -53739,7 +54623,7 @@ var ts; } if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { var containingClass = ts.getContainingClass(node); var classType = getTypeOfNode(containingClass); typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); @@ -53754,8 +54638,8 @@ var ts; // extends clause of a class. We handle that case here. var classNode = ts.getContainingClass(node); var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); + var baseType = ts.firstOrUndefined(getBaseTypes(classType)); + return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -53764,7 +54648,7 @@ var ts; } if (isTypeDeclarationName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } if (ts.isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -53773,10 +54657,10 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); + return symbol ? getTypeOfSymbol(symbol) : errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -54394,7 +55278,8 @@ var ts; setAccessor: setAccessor, getAccessor: getAccessor }; - } + }, + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55505,9 +56390,6 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - if (node.name.kind === 183 /* ArrayBindingPattern */ || node.name.kind === 182 /* ObjectBindingPattern */) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (node.propertyName) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); } @@ -55779,10 +56661,10 @@ var ts; // this has already been reported, and don't report if it has. // if (node.parent.kind === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { - var links_1 = getNodeLinks(node.parent); + var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + if (!links_2.hasReportedStatementInAmbientContext) { + return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); } } else { @@ -56914,19 +57796,7 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - 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; - } + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters @@ -57038,17 +57908,7 @@ var ts; return node; } ts.createConditional = createConditional; - 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]; + function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) { return node.condition !== condition || node.questionToken !== questionToken || node.whenTrue !== whenTrue @@ -57851,7 +58711,7 @@ var ts; function createJsxSelfClosingElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -57867,7 +58727,7 @@ var ts; function createJsxOpeningElement(tagName, typeArguments, attributes) { var node = createSynthesizedNode(260 /* JsxOpeningElement */); node.tagName = tagName; - node.typeArguments = typeArguments && createNodeArray(typeArguments); + node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; return node; } @@ -58162,7 +59022,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(304 /* NotEmittedStatement */); + var node = createSynthesizedNode(305 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -58174,7 +59034,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(308 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(309 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -58186,7 +59046,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(307 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(308 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -58201,7 +59061,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(305 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(306 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -58217,7 +59077,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 306 /* CommaListExpression */) { + if (node.kind === 307 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -58227,7 +59087,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(306 /* CommaListExpression */); + var node = createSynthesizedNode(307 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -59397,6 +60257,11 @@ var ts; var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); + if (!isLeftSideOfBinary && operand.kind === 195 /* ArrowFunction */ && binaryOperatorPrecedence > 4) { + // We need to parenthesize arrow functions on the right side to avoid it being + // parsed as parenthesized expression: `a && (() => {})` + return true; + } var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1 /* LessThan */: @@ -59539,11 +60404,15 @@ var ts; */ function parenthesizeDefaultExpression(e) { var check = ts.skipPartiallyEmittedExpressions(e); - return check.kind === 207 /* ClassExpression */ || - check.kind === 194 /* FunctionExpression */ || - isCommaSequence(check) - ? ts.createParen(e) - : e; + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; } ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; /** @@ -59696,6 +60565,9 @@ var ts; case 203 /* ConditionalExpression */: node = node.condition; continue; + case 191 /* TaggedTemplateExpression */: + node = node.tag; + continue; case 189 /* CallExpression */: if (stopAtCallExpressions) { return node; @@ -59705,7 +60577,7 @@ var ts; case 188 /* ElementAccessExpression */: case 187 /* PropertyAccessExpression */: case 211 /* NonNullExpression */: - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -59721,7 +60593,7 @@ var ts; ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || - node.kind === 306 /* CommaListExpression */; + node.kind === 307 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -59740,7 +60612,7 @@ var ts; case 210 /* AsExpression */: case 211 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -59777,7 +60649,7 @@ var ts; case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 305 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -60054,7 +60926,7 @@ var ts; // `1` in `let { 1: b } = ...` if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -60066,7 +60938,7 @@ var ts; // `1` in `({ 1: b } = ...)` if (bindingElement.name) { var propertyName = bindingElement.name; - return ts.isComputedPropertyName(propertyName) && ts.isStringOrNumericLiteral(propertyName.expression) + return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -60077,13 +60949,18 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && ts.isStringOrNumericLiteral(target.expression) + return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) ? target.expression : target; } ts.Debug.fail("Invalid property name for binding element."); } ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */; + } /** * Gets the elements of a BindingOrAssignmentPattern */ @@ -60567,9 +61444,9 @@ var ts; case 277 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -60625,7 +61502,7 @@ var ts; case 218 /* EmptyStatement */: case 208 /* OmittedExpression */: case 234 /* DebuggerStatement */: - case 304 /* NotEmittedStatement */: + case 305 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -61004,10 +61881,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -61021,8 +61898,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) - : ts.prependStatements(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -61200,7 +62077,7 @@ var ts; function decode(host, mapPath, map, program, fallbackCache) { if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } var currentDirectory = ts.getDirectoryPath(mapPath); - var sourceRoot = map.sourceRoot || currentDirectory; + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; var decodedMappings; var generatedOrderedMappings; var sourceOrderedMappings; @@ -61235,10 +62112,11 @@ var ts; } function getSourceFileLike(fileName, location) { // Lookup file in program, if provided - var file = program && program.getSourceFile(fileName); - if (!file) { + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + var file = program && program.getSourceFile(path); + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + if (!file || file.resolvedPath !== path) { // Otherwise check the cache (which may hit disk) - var path = ts.toPath(fileName, location, host.getCanonicalFileName); return fallbackCache.get(path); } return file; @@ -62074,7 +62952,7 @@ var ts; var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); return ts.createElementAccess(value, argumentExpression); } - else if (ts.isStringOrNumericLiteral(propertyName)) { + else if (ts.isStringOrNumericLiteralLike(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); @@ -62754,7 +63632,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, context.endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -63206,6 +64084,7 @@ var ts; var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); statements.push(statement); } } @@ -63223,6 +64102,7 @@ var ts; ts.startOnNewLine(expression); ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); ts.setCommentRange(expression, property); + ts.setOriginalNode(expression, property); expressions.push(expression); } return expressions; @@ -63643,6 +64523,11 @@ var ts; } return false; } + function getAccessorTypeNode(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor) + || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor); + } /** * Serializes the type of a node for use with decorator type metadata. * @@ -63652,10 +64537,10 @@ var ts; switch (node.kind) { case 152 /* PropertyDeclaration */: case 149 /* Parameter */: - case 156 /* GetAccessor */: return serializeTypeNode(node.type); case 157 /* SetAccessor */: - return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + case 156 /* GetAccessor */: + return serializeTypeNode(getAccessorTypeNode(node)); case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 154 /* MethodDeclaration */: @@ -63846,11 +64731,11 @@ var ts; var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: - var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); + return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); case ts.TypeReferenceSerializationKind.BooleanType: @@ -63875,14 +64760,35 @@ var ts; return ts.Debug.assertNever(kind); } } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 71 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 71 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } /** * Serializes an entity name as an expression for decorator type metadata. * * @param node The entity name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * entity name at runtime. */ - function serializeEntityNameAsExpression(node, useFallback) { + function serializeEntityNameAsExpression(node) { switch (node.kind) { case 71 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were @@ -63891,12 +64797,9 @@ var ts; name.flags &= ~8 /* Synthesized */; name.original = undefined; name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. - if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); - } return name; case 146 /* QualifiedName */: - return serializeQualifiedNameAsExpression(node, useFallback); + return serializeQualifiedNameAsExpression(node); } } /** @@ -63906,19 +64809,8 @@ var ts; * @param useFallback A value indicating whether to use logical operators to test for the * qualified name at runtime. */ - function serializeQualifiedNameAsExpression(node, useFallback) { - var left; - if (node.left.kind === 71 /* Identifier */) { - left = serializeEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); - } - else { - left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); - } - return ts.createPropertyAccess(left, node.right); + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); } /** * Gets an expression that points to the global "Symbol" constructor at runtime if it is @@ -64327,7 +65219,8 @@ var ts; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; @@ -64362,8 +65255,13 @@ var ts; /*type*/ undefined, transformEnumBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(enumStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(enumStatement, undefined); + ts.setSyntheticTrailingComments(enumStatement, undefined); + } ts.setTextRange(enumStatement, node); - ts.setEmitFlags(enumStatement, emitFlags); + ts.addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); // Add a DeclarationMarker for the enum to preserve trailing comments and mark // the end of the declaration. @@ -64381,7 +65279,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -64510,7 +65408,7 @@ var ts; // })(m1 || (m1 = {})); // trailing comment module // ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); + ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(statement); return true; } @@ -64545,7 +65443,8 @@ var ts; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. - if (addVarForEnumOrModuleDeclaration(statements, node)) { + var varAdded = addVarForEnumOrModuleDeclaration(statements, node); + if (varAdded) { // We should still emit the comments if we are emitting a system module. if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; @@ -64579,8 +65478,13 @@ var ts; /*type*/ undefined, transformModuleBody(node, containerName)), /*typeArguments*/ undefined, [moduleArg])); ts.setOriginalNode(moduleStatement, node); + if (varAdded) { + // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement. + ts.setSyntheticLeadingComments(moduleStatement, undefined); + ts.setSyntheticTrailingComments(moduleStatement, undefined); + } ts.setTextRange(moduleStatement, node); - ts.setEmitFlags(moduleStatement, emitFlags); + ts.addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); // Add a DeclarationMarker for the namespace to preserve trailing comments and mark // the end of the declaration. @@ -64622,7 +65526,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -65432,7 +66336,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -66039,7 +66943,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -66067,7 +66971,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.prependStatements(statements, leadingStatements); + ts.addStatementsAfterPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -67162,7 +68066,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -67417,7 +68321,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -67530,7 +68434,7 @@ var ts; && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -67640,7 +68544,7 @@ var ts; return 2 /* ReplaceWithReturn */; } // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis(), firstStatement); + captureThisForNode(statements, ctor, superCallExpression || createActualThis()); // If we're actually replacing the original statement, we need to signal this to the caller. if (superCallExpression) { return 1 /* ReplaceSuperCapture */; @@ -67832,7 +68736,7 @@ var ts; captureThisForNode(statements, node, ts.createThis()); } } - function captureThisForNode(statements, node, initializer, originalStatement) { + function captureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -67840,7 +68744,6 @@ var ts; /*type*/ undefined, initializer) ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); - ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); } @@ -68170,7 +69073,7 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.prependStatements(statements, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { @@ -68432,7 +69335,7 @@ var ts; var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false) ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node) - : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement), node, convertedLoopState && resetLabel); + : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel); } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { @@ -68749,7 +69652,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.prependStatements(statements_4, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -70424,7 +71327,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -72662,7 +73565,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -72885,7 +73788,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -72948,9 +73851,9 @@ var ts; return visitFunctionDeclaration(node); case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 307 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 308 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -73176,7 +74079,7 @@ var ts; if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { // import "mod"; - return ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node); } else { var variables = []; @@ -73197,18 +74100,20 @@ var ts; /*type*/ undefined, ts.getGeneratedNameForNode(node))); } } - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), - /*location*/ node)); + /*location*/ node), + /*original*/ node)); } } else if (namespaceDeclaration && ts.isDefaultImport(node)) { // import d, * as n from "mod"; statements = ts.append(statements, ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), + ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node)), - /*location*/ node) + /*location*/ node), + /*original*/ node) ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -73244,20 +74149,20 @@ var ts; var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node)); } else { - statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), /*type*/ undefined, createRequireCall(node)) ], - /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node)); + /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); } } else { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node)); } } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -73286,23 +74191,24 @@ var ts; var statements = []; // export { x, y } from "mod"; if (moduleKind !== ts.ModuleKind.AMD) { - statements.push(ts.setTextRange(ts.createVariableStatement( + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(generatedName, /*type*/ undefined, createRequireCall(node)) ])), - /*location*/ node)); + /*location*/ node), + /* original */ node)); } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); } return ts.singleOrMany(statements); } else { // export * from "mod"; - return ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); + return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node); } } /** @@ -73408,7 +74314,7 @@ var ts; statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); } if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node)); } } else { @@ -74154,7 +75060,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.prependStatements(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -74882,9 +75788,9 @@ var ts; return visitCatchClause(node); case 216 /* Block */: return visitBlock(node); - case 307 /* MergeDeclarationMarker */: + case 308 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 308 /* EndOfDeclarationMarker */: + case 309 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -75928,7 +76834,8 @@ var ts; 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | - 4 /* GenerateNamesForShadowedTypeParams */; + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; /** * Transforms a ts file into a .d.ts file * This process requires type information, which is retrieved through the emit resolver. Because of this, @@ -75948,6 +76855,7 @@ var ts; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; + var exportedModulesFromDeclarationEmit; var host = context.getEmitHost(); var symbolTracker = { trackSymbol: trackSymbol, @@ -75956,6 +76864,7 @@ var ts; reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode }; var errorNameNode; var currentSourceFile; @@ -76014,6 +76923,11 @@ var ts; } } } + function trackExternalModuleSymbolOfImportTypeNode(symbol) { + if (!isBundledEmit) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } + } function trackSymbol(symbol, enclosingDeclaration, meaning) { if (symbol.flags & 262144 /* TypeParameter */) return; @@ -76041,7 +76955,7 @@ var ts; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; - var refs_1 = ts.createMap(); + refs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) @@ -76055,7 +76969,7 @@ var ts; getSymbolAccessibilityDiagnostic = throwDiagnostic; needsScopeFixMarker = false; resultHasScopeMarker = false; - collectReferences(sourceFile, refs_1); + collectReferences(sourceFile, refs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; @@ -76076,7 +76990,7 @@ var ts; bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); - refs_1.forEach(referenceVisitor_1); + refs.forEach(referenceVisitor_1); return bundle; } // Single source file @@ -76104,6 +77018,7 @@ var ts; combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; function getFileReferencesForUsedTypeReferences() { return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; @@ -76321,10 +77236,18 @@ var ts; if (!input) return undefined; // TODO: GH#18217 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); - if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { - var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); - if (newName) { - return ts.createLiteral(newName); + if (ts.isStringLiteralLike(input)) { + if (isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + else { + var symbol = resolver.getSymbolOfExternalModuleSpecifier(input); + if (symbol) { + (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol); + } } } return input; @@ -76853,6 +77776,15 @@ var ts; } return false; } + function isScopeMarker(node) { + return ts.isExportAssignment(node) || ts.isExportDeclaration(node); + } + function hasScopeMarker(node) { + if (ts.isModuleBlock(node)) { + return ts.some(node.statements, isScopeMarker); + } + return false; + } function ensureModifiers(node, privateDeclaration) { var currentFlags = ts.getModifierFlags(node); var newFlags = ensureModifierFlags(node, privateDeclaration); @@ -76866,7 +77798,7 @@ var ts; var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; var parentIsFile = node.parent.kind === 277 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { - mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; } return maskModifierFlags(node, mask, additions); @@ -76885,7 +77817,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_8 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -76899,7 +77831,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_8(range); } } return prop; @@ -76925,6 +77857,11 @@ var ts; if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { + // A non-exported default is a nonsequitor - we usually try to remove all export modifiers + // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid + flags ^= 1 /* Export */; + } if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) } @@ -77061,7 +77998,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(309 /* Count */); + var enabledSyntaxKindFeatures = new Array(310 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -77408,7 +78345,7 @@ var ts; if (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { // The relative paths are relative to the common directory @@ -77614,7 +78551,7 @@ var ts; source = undefined; if (source) setSourceFile(source); - if (node.kind !== 304 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -77631,7 +78568,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 304 /* NotEmittedStatement */ + if (node.kind !== 305 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -77810,7 +78747,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 304 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 305 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -77824,10 +78761,12 @@ var ts; var savedContainerPos = containerPos; var savedContainerEnd = containerEnd; var savedDeclarationListContainerEnd = declarationListContainerEnd; - if (!skipLeadingComments) { + if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { + // Advance the container position of comments get emitted or if they've been disabled explicitly using NoLeadingComments. containerPos = pos; } - if (!skipTrailingComments) { + if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) { + // As above. containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end @@ -78176,17 +79115,17 @@ var ts; if (sourceFile.kind === 278 /* Bundle */) { var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error var isJs = ts.isSourceFileJavaScript(sourceFile); - var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } @@ -78241,6 +79180,7 @@ var ts; }); var bundleInfo = createDefaultBundleInfo(); var emitSkipped = false; + var exportedModulesFromDeclarationEmit; // Emit each output file ts.performance.mark("beforePrint"); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); @@ -78250,6 +79190,7 @@ var ts; diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList, + exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; @@ -78308,7 +79249,7 @@ var ts; // Setup and perform the transformation to retrieve declarations from the input files var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; - if (emitOnlyDtsFiles && !compilerOptions.declaration) { + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. // Do that here when emitting only dts files nonJsFiles.forEach(collectLinkedAliases); @@ -78337,6 +79278,10 @@ var ts; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 277 /* SourceFile */) { + var sourceFile = declarationTransform.transformed[0]; + exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; + } } declarationTransform.dispose(); } @@ -78975,9 +79920,9 @@ var ts; case 262 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 305 /* PartiallyEmittedExpression */: + case 306 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 306 /* CommaListExpression */: + case 307 /* CommaListExpression */: return emitCommaList(node); } } @@ -81692,7 +82637,7 @@ var ts; case WatchLogLevel.TriggerOnly: return createFileWatcherWithTriggerLogging; case WatchLogLevel.Verbose: - return createFileWatcherWithLogging; + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; } } function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { @@ -81705,9 +82650,27 @@ var ts; } }; } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { return addWatch(host, file, function (fileName, cbOptional) { - var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); log(triggerredInfo); var start = ts.timestamp(); cb(fileName, cbOptional, passThrough); @@ -81837,7 +82800,7 @@ var ts; } } ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82199,6 +83162,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -82236,7 +83200,8 @@ var ts; var packageIdToSourceFile = ts.createMap(); // Maps from a SourceFile's `.path` to the name of the package it was imported with. var sourceFileToPackageName = ts.createMap(); - var redirectTargetsSet = ts.createMap(); + // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. + var redirectTargetsMap = ts.createMultiMap(); var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -82343,7 +83308,7 @@ var ts; getSourceFileFromReference: getSourceFileFromReference, getLibFileFromReference: getLibFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, + redirectTargetsMap: redirectTargetsMap, isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, @@ -82629,7 +83594,7 @@ var ts; fileChanged = false; newSourceFile = oldSourceFile; // Use the redirect. } - else if (oldProgram.redirectTargetsSet.has(oldSourceFile.path)) { + else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { // If a redirected-to source file changes, the redirect may be broken. if (newSourceFile !== oldSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -82758,7 +83723,7 @@ var ts; resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; - redirectTargetsSet = oldProgram.redirectTargetsSet; + redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -82950,10 +83915,7 @@ var ts; } function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { - // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a - // '/// ' directive. - if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { + if (ts.skipTypeChecking(sourceFile, options)) { return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); @@ -83347,7 +84309,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -83425,9 +84387,17 @@ var ts; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path - // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } } // If the file was previously found via a node_modules search, but is now being processed as a root file, // then everything it sucks in may also be marked incorrectly, and needs to be checked again. @@ -83480,7 +84450,7 @@ var ts; // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 - redirectTargetsSet.set(fileFromPackageId.path, true); + redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles.push(dupFile); @@ -83710,7 +84680,7 @@ var ts; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); allFilesBelongToPath = false; } } @@ -83727,6 +84697,7 @@ var ts; if (sourceFile === undefined) { return undefined; } + sourceFile.path = toPath(refPath); var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } @@ -83740,7 +84711,7 @@ var ts; ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 } function verifyCompilerOptions() { - if (options.strictPropertyInitialization && !options.strictNullChecks) { + if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { @@ -83800,14 +84771,14 @@ var ts; if (options.composite && rootNames.length < files.length) { var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_10 = function (file) { + var _loop_9 = function (file) { if (normalizedRootNames.every(function (r) { return r !== file; })) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); } }; for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var file = sourceFiles_4[_i]; - _loop_10(file); + _loop_9(file); } } if (options.paths) { @@ -83864,7 +84835,7 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } - if (options.declarationMap && !options.declaration) { + if (options.declarationMap && !ts.getEmitDeclarations(options)) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); } if (options.lib && options.noLib) { @@ -83905,6 +84876,10 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } + // Any emit other than common js is error + else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + } } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted @@ -84036,12 +85011,12 @@ var ts; } function createDiagnosticForReference(index, message, arg0, arg1) { var referencesSyntax = getProjectReferencesSyntax(); - if (referencesSyntax) { - if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { - return; - } + if (referencesSyntax && referencesSyntax.elements.length > index) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, referencesSyntax.elements[index], message, arg0, arg1)); + } + else { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); } function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); @@ -84091,14 +85066,6 @@ var ts; } return !!props.length; } - function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { - if (arrayLiteral.elements.length <= index) { - // Out-of-bounds - return false; - } - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); - return false; // TODO: GH#18217 This function always returns `false`!` - } function blockEmittingOfFile(emitFileName, diag) { hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); @@ -84151,7 +85118,8 @@ var ts; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; /** - * Returns the target config filename of a project reference + * Returns the target config filename of a project reference. + * Note: The file might not exist. */ function resolveProjectReferencePath(host, ref) { if (!host.fileExists(ref.path)) { @@ -84171,7 +85139,6 @@ var ts; switch (extension) { case ".ts" /* Ts */: case ".d.ts" /* Dts */: - case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check // These are always allowed. return undefined; case ".tsx" /* Tsx */: @@ -84180,6 +85147,8 @@ var ts; return needJsx() || needAllowJs(); case ".js" /* Js */: return needAllowJs(); + case ".json" /* Json */: + return needResolveJsonModule(); } function needJsx() { return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; @@ -84187,6 +85156,9 @@ var ts; function needAllowJs() { return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } + function needResolveJsonModule() { + return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used; + } } ts.getResolutionDiagnostic = getResolutionDiagnostic; function getModuleNames(_a) { @@ -84208,7 +85180,7 @@ var ts; function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -84219,6 +85191,22 @@ var ts; (function (ts) { var BuilderState; (function (BuilderState) { + /** + * Get the referencedFile from the imported module symbol + */ + function getReferencedFileFromImportedModuleSymbol(symbol) { + if (symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + return declarationSourceFile && declarationSourceFile.path; + } + } + /** + * Get the referencedFile from the import name node from file + */ + function getReferencedFileFromImportLiteral(checker, importName) { + var symbol = checker.getSymbolAtLocation(importName); + return symbol && getReferencedFileFromImportedModuleSymbol(symbol); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -84231,12 +85219,9 @@ var ts; var checker = program.getTypeChecker(); for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } + var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName); + if (declarationSourceFilePath) { + addReferencedFile(declarationSourceFilePath); } } } @@ -84281,6 +85266,7 @@ var ts; function create(newProgram, getCanonicalFileName, oldState) { var fileInfos = ts.createMap(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var exportedModulesMap = referencedMap ? ts.createMap() : undefined; var hasCalledUpdateShapeSignature = ts.createMap(); var useOldState = canReuseOldState(referencedMap, oldState); // Create the reference map, and set the file infos @@ -84293,12 +85279,20 @@ var ts; if (newReferences) { referencedMap.set(sourceFile.path, newReferences); } + // Copy old visible to outside files map + if (useOldState) { + var exportedModules = oldState.exportedModulesMap.get(sourceFile.path); + if (exportedModules) { + exportedModulesMap.set(sourceFile.path, exportedModules); + } + } } fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); } return { fileInfos: fileInfos, referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, allFilesExcludingDefaultLibraryFile: undefined, allFileNames: undefined @@ -84308,7 +85302,7 @@ var ts; /** * Gets the files affected by the path from the program */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { // Since the operation could be cancelled, the signatures are always stored in the cache // They will be commited once it is safe to use them // eg when calling this api from tsserver, if there is no cancellation of the operation @@ -84318,10 +85312,10 @@ var ts; if (!sourceFile) { return ts.emptyArray; } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) { return [sourceFile]; } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache); if (!cacheToUpdateSignature) { // Commit all the signatures in the signature cache updateSignaturesFromCache(state, signatureCache); @@ -84343,8 +85337,9 @@ var ts; /** * Returns if the shape of the signature has changed since last emit */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { ts.Debug.assert(!!sourceFile); + ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state"); // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { return false; @@ -84361,6 +85356,9 @@ var ts; var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = computeHash(emitOutput.outputFiles[0].text); + if (exportedModulesMapCache && latestSignature !== prevSignature) { + updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); + } } else { latestSignature = prevSignature; // TODO: GH#18217 @@ -84369,6 +85367,44 @@ var ts; cacheToUpdateSignature.set(sourceFile.path, latestSignature); return !prevSignature || latestSignature !== prevSignature; } + /** + * Coverts the declaration emit result into exported modules map + */ + function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { + if (!exportedModulesFromDeclarationEmit) { + exportedModulesMapCache.set(sourceFile.path, false); + return; + } + var exportedModules; + exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); }); + exportedModulesMapCache.set(sourceFile.path, exportedModules || false); + function addExportedModule(exportedModulePath) { + if (exportedModulePath) { + if (!exportedModules) { + exportedModules = ts.createMap(); + } + exportedModules.set(exportedModulePath, true); + } + } + } + /** + * Updates the exported modules from cache into state's exported modules map + * This should be called whenever it is safe to commit the state of the builder + */ + function updateExportedFilesMapFromCache(state, exportedModulesMapCache) { + if (exportedModulesMapCache) { + ts.Debug.assert(!!state.exportedModulesMap); + exportedModulesMapCache.forEach(function (exportedModules, path) { + if (exportedModules) { + state.exportedModulesMap.set(path, exportedModules); + } + else { + state.exportedModulesMap.delete(path); + } + }); + } + } + BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache; /** * Get all the dependencies of the sourceFile */ @@ -84478,7 +85514,7 @@ var ts; /** * When program emits modular code, gets the files affected by the sourceFile whose shape has changed */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) { if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); } @@ -84498,7 +85534,7 @@ var ts; if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 queue, getReferencedByPaths(state, currentPath)); } @@ -84529,7 +85565,8 @@ var ts; } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && + !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldState.program.getCompilerOptions()); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { @@ -84565,6 +85602,10 @@ var ts; var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + if (!state.semanticDiagnosticsFromOldState) { + state.semanticDiagnosticsFromOldState = ts.createMap(); + } + state.semanticDiagnosticsFromOldState.set(sourceFilePath, true); } } }); @@ -84586,14 +85627,14 @@ var ts; while (true) { var affectedFiles = state.affectedFiles; if (affectedFiles) { - var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var seenAffectedFiles = state.seenAffectedFiles; var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 while (affectedFilesIndex < affectedFiles.length) { var affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.path)) { // Set the next affected file as seen and remove the cached semantic diagnostics state.affectedFilesIndex = affectedFilesIndex; - semanticDiagnosticsPerFile.delete(affectedFile.path); + cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile); return affectedFile; } seenAffectedFiles.set(affectedFile.path, true); @@ -84605,6 +85646,7 @@ var ts; // Commit the changes in file signature ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); state.currentAffectedFilesSignatures.clear(); + ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap); state.affectedFiles = undefined; } // Get next changed file @@ -84622,13 +85664,66 @@ var ts; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + if (state.exportedModulesMap) { + state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); + } + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; - state.semanticDiagnosticsPerFile.delete(nextKey.value); state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file + */ + function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { + if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { + // If there are no more diagnostics from old cache, done + return; + } + // If there was change in signature for the changed file, + // then delete the semantic diagnostics for files that are affected by using exports of this module + if (!state.exportedModulesMap || state.affectedFiles.length === 1 || !state.changedFilesSet.has(affectedFile.path)) { + return; + } + ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) { + return exportedModules && + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + })) { + return; + } + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(affectedFile.path) && + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath); + }); + } + /** + * removes the semantic diagnostics of files referencing referencedPath and + * returns true if there are no more semantic diagnostics from old state + */ + function removeSemanticDiagnosticsOfFilesReferencingPath(state, referencedPath) { + return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) { + return referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath); + }); + } + /** + * Removes semantic diagnostics for path and + * returns true if there are no more semantic diagnostics from the old state + */ + function removeSemanticDiagnosticsOf(state, path) { + if (!state.semanticDiagnosticsFromOldState) { + return false; + } + state.semanticDiagnosticsFromOldState.delete(path); + state.semanticDiagnosticsPerFile.delete(path); + return !state.semanticDiagnosticsFromOldState.size; + } /** * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly @@ -84895,6 +85990,7 @@ var ts; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -84952,6 +86048,7 @@ var ts; function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); @@ -84991,17 +86088,19 @@ var ts; perDirectoryResolvedModuleNames.clear(); nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); - clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); @@ -85053,7 +86152,7 @@ var ts; perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); - watchFailedLookupLocationOfResolution(resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } @@ -85149,14 +86248,23 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - // Always watch root directory recursively - return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line + var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); + if (subDirectoryInRoot !== -1) { + // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution + return { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) }; + } + else { + // Always watch root directory non recursively + return { dir: rootDir, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217 + } } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) { // If directory path contains node module, get the most parent node_modules directory for watching - while (ts.stringContains(dirPath, "/node_modules/")) { + while (ts.stringContains(dirPath, ts.nodeModulesPathPart)) { dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } @@ -85185,16 +86293,25 @@ var ts; function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); } - function watchFailedLookupLocationOfResolution(resolution) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { // No need to set the resolution refCount - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { - return; - } - if (resolution.refCount !== undefined) { - resolution.refCount++; - return; + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } } - resolution.refCount = 1; + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); var failedLookupLocations = resolution.failedLookupLocations; var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { @@ -85209,6 +86326,7 @@ var ts; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); } if (dirPath === rootPath) { + ts.Debug.assert(!nonRecursive); setAtRoot = true; } else { @@ -85217,10 +86335,19 @@ var ts; } } if (setAtRoot) { - // This is always recursive - setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 + // This is always non recursive + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } } + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var program = resolutionHost.getCurrentProgram(); + var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { @@ -85232,7 +86359,7 @@ var ts; } } function stopWatchFailedLookupLocationOfResolution(resolution) { - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + if (!resolution.refCount) { return; } resolution.refCount--; @@ -85455,23 +86582,36 @@ var ts; } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); -// Used by importFixes to synthesize import module specifiers. +// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { // Note: importingSourceFile is just for usesJsExtensionOnImports - function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences) { + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, toFileName, info.getCanonicalFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { + var isBundle = (compilerOptions.out || compilerOptions.outFile); + if (isBundle && host.getCommonSourceDirectory) { + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); + } + var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; + return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + } + moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) return [[ambient]]; @@ -85479,7 +86619,8 @@ var ts; if (!files) { return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); } - var modulePaths = getAllModulePaths(files, ts.getSourceFileOfNode(moduleSymbol.valueDeclaration).fileName, info.getCanonicalFileName, host); + var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); @@ -85564,64 +86705,66 @@ var ts; return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; }) || false; } - function discoverProbableSymlinks(files, getCanonicalFileName, host) { + function stringsEqual(a, b, getCanonicalFileName) { + return getCanonicalFileName(a) === getCanonicalFileName(b); + } + // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. + // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. + function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { + return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); + } + function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && + !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && + stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) { + aParts.pop(); + bParts.pop(); + } + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; + } + function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { + var result = ts.createMap(); var symlinks = ts.mapDefined(files, function (sf) { return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; }); }); - var result = ts.createMap(); - if (symlinks) { - var currentDirectory = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { - var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; - var resolvedParts = ts.getPathComponents(ts.toPath(resolvedPath, currentDirectory, getCanonicalFileName)); - var originalParts = ts.getPathComponents(ts.toPath(originalPath, currentDirectory, getCanonicalFileName)); - while (compareStrings(resolvedParts[resolvedParts.length - 1], originalParts[originalParts.length - 1]) === 0 /* EqualTo */) { - resolvedParts.pop(); - originalParts.pop(); - } - result.set(ts.getPathFromPathComponents(originalParts), ts.getPathFromPathComponents(resolvedParts)); - } + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1]; + result.set(commonOriginal, commonResolved); } return result; } - function getAllModulePathsUsingIndirectSymlinks(files, target, getCanonicalFileName, host) { - var links = discoverProbableSymlinks(files, getCanonicalFileName, host); - var paths = ts.arrayFrom(links.keys()); - var options; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - for (var _i = 0, paths_2 = paths; _i < paths_2.length; _i++) { - var path = paths_2[_i]; - var resolved = links.get(path); - if (compareStrings(target.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */) { - var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - if (!options) - options = []; - options.push(option); - } - } - } - if (options) { - options.push(target); // Since these are speculative, we also include the original resolved name as a possibility - return options; - } - return [target]; - } /** * Looks for existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(files, importedFileName, getCanonicalFileName, host) { - var symlinks = ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === importedFileName ? res.originalPath : undefined; - }); + * Symlinks will be returned first so they are preferred over the real path. + */ + function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { + var redirects = redirectTargetsMap.get(importedFileName); + var importedFileNames = redirects ? redirects.concat([importedFileName]) : [importedFileName]; + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var links = discoverProbableSymlinks(files, getCanonicalFileName, cwd); + var result = []; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + links.forEach(function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return; // Don't want to a package to globally import from itself + } + var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + result.push(option); + } }); - return symlinks.length === 0 ? getAllModulePathsUsingIndirectSymlinks(files, ts.getNormalizedAbsolutePath(importedFileName, host.getCurrentDirectory ? host.getCurrentDirectory() : ""), getCanonicalFileName, host) : symlinks; + result.push.apply(result, targets); + return result; } function getRelativePathNParents(relativePath) { var components = ts.getPathComponents(relativePath); @@ -85634,8 +86777,8 @@ var ts; return components.length - 1; } function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + if (decl) { return decl.name.text; } } @@ -85645,10 +86788,7 @@ var ts; var patternText_1 = _a[_i]; var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { + if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && @@ -85761,7 +86901,7 @@ var ts; partEnd = fullPath.indexOf("/", partStart + 1); switch (state) { case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { topLevelNodeModulesIndex = partStart; topLevelPackageNameIndex = partEnd; state = 1 /* NodeModules */; @@ -85778,7 +86918,7 @@ var ts; } break; case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { state = 1 /* NodeModules */; } else { @@ -85963,6 +87103,7 @@ var ts; createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; } var host = system; + host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); @@ -86091,16 +87232,15 @@ var ts; }; // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); - if (configFileName) { + if (configFileName && !host.configFileParsingResult) { newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); - if (host.configFileParsingResult) { - setConfigFileParsingResult(host.configFileParsingResult); - } - else { - ts.Debug.assert(!rootFileNames); - parseConfigFile(); - } + ts.Debug.assert(!rootFileNames); + parseConfigFile(); newLine = updateNewLine(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); @@ -86648,7 +87788,7 @@ var ts; } var outputs = []; outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); - if (configFile.options.declaration && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); if (configFile.options.declarationMap) { @@ -86663,7 +87803,7 @@ var ts; } var outputs = []; outputs.push(project.options.outFile); - if (project.options.declaration) { + if (ts.getEmitDeclarations(project.options)) { var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { @@ -86815,6 +87955,7 @@ var ts; return builder.cleanAllProjects(); } if (watch) { + builder.buildAllProjects(); builder.startWatching(); return undefined; } @@ -86871,7 +88012,7 @@ var ts; // Everything is broken - we don't even know what to watch. Give up. return; } - var _loop_11 = function (resolved) { + var _loop_10 = function (resolved) { var cfg = configFileCache.parseConfigFile(resolved); if (cfg) { // Watch this file @@ -86898,7 +88039,7 @@ var ts; }; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var resolved = _a[_i]; - _loop_11(resolved); + _loop_10(resolved); } function invalidateProjectAndScheduleBuilds(resolved) { invalidateProject(resolved); @@ -87068,7 +88209,7 @@ var ts; }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { resultFlags |= BuildResultFlags.SyntaxErrors; for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { @@ -87079,7 +88220,7 @@ var ts; return resultFlags; } // Don't emit .d.ts if there are decl file errors - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { resultFlags |= BuildResultFlags.DeclarationEmitErrors; @@ -87133,15 +88274,16 @@ var ts; if (context.options.dry) { return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) + if (context.options.verbose) { buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { var file = outputs_1[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file)); + priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); } compilerHost.setModifiedTime(file, now); } @@ -87339,7 +88481,7 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile); + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; if (inputTime > newestInputFileTime) { newestInputFileName = inputFile; newestInputFileTime = inputTime; @@ -87368,7 +88510,7 @@ var ts; missingOutputFileName = output; break; } - var outputTime = host.getModifiedTime(output); + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; if (outputTime < oldestOutputFileTime) { oldestOutputFileTime = outputTime; oldestOutputFileName = output; @@ -87393,7 +88535,8 @@ var ts; newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } else { - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, host.getModifiedTime(output)); + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } @@ -87512,7 +88655,7 @@ var ts; // Don't report status on "solution" projects break; default: - ts.assertTypeIsNever(status); + ts.assertType(status); } } ts.formatUpToDateStatus = formatUpToDateStatus; @@ -87976,18 +89119,23 @@ var ts; return { command: command, remaining: remaining - toSlice }; } typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation; - function isPackageOrBowerJson(fileName) { - var base = ts.getBaseFileName(fileName); - return base === "package.json" || base === "bower.json"; - } - function getDirectoryExcludingNodeModulesOrBowerComponents(f) { - var indexOfNodeModules = f.indexOf("/node_modules/"); - var indexOfBowerComponents = f.indexOf("/bower_components/"); - var subStrLength = indexOfNodeModules === -1 || indexOfBowerComponents === -1 ? - Math.max(indexOfNodeModules, indexOfBowerComponents) : - Math.min(indexOfNodeModules, indexOfBowerComponents); - return subStrLength === -1 ? f : f.substr(0, subStrLength); - } + function endsWith(str, suffix, caseSensitive) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && + (str.indexOf(suffix, expectedPos) === expectedPos || + (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */)); + } + function isPackageOrBowerJson(fileName, caseSensitive) { + return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive); + } + function sameFiles(a, b, caseSensitive) { + return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */); + } + var ProjectWatcherType; + (function (ProjectWatcherType) { + ProjectWatcherType["FileWatcher"] = "FileWatcher"; + ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher"; + })(ProjectWatcherType || (ProjectWatcherType = {})); var TypingsInstaller = /** @class */ (function () { function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) { if (log === void 0) { log = nullLog; } @@ -88006,7 +89154,7 @@ var ts; this.inFlightRequestCount = 0; this.latestDistTag = "latest"; this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames); - this.globalCacheCanonicalPackageJsonPath = ts.combinePaths(this.toCanonicalFileName(globalCachePath), "package.json"); + this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json"); if (this.log.isEnabled()) { this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation); } @@ -88283,78 +89431,73 @@ var ts; // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings watchers.isInvoked = false; var isLoggingEnabled = this.log.isEnabled(); - var createProjectWatcher = function (path, createWatch) { - toRemove.delete(path); - if (watchers.has(path)) { + var createProjectWatcher = function (path, projectWatcherType) { + var canonicalPath = _this.toCanonicalFileName(path); + toRemove.delete(canonicalPath); + if (watchers.has(canonicalPath)) { return; } - watchers.set(path, createWatch(path)); - }; - var createProjectFileWatcher = function (file) { - if (isLoggingEnabled) { - _this.log.writeLine("FileWatcher:: Added:: WatchInfo: " + file); - } - var watcher = _this.installTypingHost.watchFile(file, function (f, eventKind) { - if (isLoggingEnabled) { - _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + file + ":: handler is already invoked '" + watchers.isInvoked + "'"); - } - if (!watchers.isInvoked) { - watchers.isInvoked = true; - _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); - } - }, /*pollingInterval*/ 2000); - return isLoggingEnabled ? { - close: function () { - _this.log.writeLine("FileWatcher:: Closed:: WatchInfo: " + file); - watcher.close(); - } - } : watcher; - }; - var createProjectDirectoryWatcher = function (dir) { if (isLoggingEnabled) { - _this.log.writeLine("DirectoryWatcher:: Added:: WatchInfo: " + dir + " recursive"); + _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path); } - var watcher = _this.installTypingHost.watchDirectory(dir, function (f) { - if (isLoggingEnabled) { - _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + dir + " recursive :: handler is already invoked '" + watchers.isInvoked + "'"); - } - if (watchers.isInvoked) { - return; - } - f = _this.toCanonicalFileName(f); - if (f !== _this.globalCacheCanonicalPackageJsonPath && isPackageOrBowerJson(f)) { - watchers.isInvoked = true; - _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); - } - }, /*recursive*/ true); - return isLoggingEnabled ? { + var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ? + _this.installTypingHost.watchFile(path, function (f, eventKind) { + if (isLoggingEnabled) { + _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'"); + } + if (!watchers.isInvoked) { + watchers.isInvoked = true; + _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); + } + }, /*pollingInterval*/ 2000) : + _this.installTypingHost.watchDirectory(path, function (f) { + if (isLoggingEnabled) { + _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'"); + } + if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) { + return; + } + if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) && + !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) { + watchers.isInvoked = true; + _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate }); + } + }, /*recursive*/ true); + watchers.set(canonicalPath, isLoggingEnabled ? { close: function () { - _this.log.writeLine("DirectoryWatcher:: Closed:: WatchInfo: " + dir + " recursive"); + _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path); watcher.close(); } - } : watcher; + } : watcher); }; // Create watches from list of files for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { var file = files_1[_i]; - var filePath = this.toCanonicalFileName(file); - if (isPackageOrBowerJson(filePath)) { + if (file.endsWith("/package.json") || file.endsWith("/bower.json")) { // package.json or bower.json exists, watch the file to detect changes and update typings - createProjectWatcher(filePath, createProjectFileWatcher); + createProjectWatcher(file, "FileWatcher" /* FileWatcher */); continue; } // path in projectRoot, watch project root - if (ts.containsPath(projectRootPath, filePath, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { - createProjectWatcher(projectRootPath, createProjectDirectoryWatcher); + if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { + var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1); + if (subDirectory !== -1) { + // Watch subDirectory + createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */); + } + else { + // Watch the directory itself + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); + } continue; } // path in global cache, watch global cache - if (ts.containsPath(this.globalCachePath, filePath, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { - createProjectWatcher(this.globalCachePath, createProjectDirectoryWatcher); + if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { + createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */); continue; } - // Get path without node_modules and bower_components - createProjectWatcher(getDirectoryExcludingNodeModulesOrBowerComponents(ts.getDirectoryPath(filePath)), createProjectDirectoryWatcher); + // watch node_modules or bower_components + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); } // Remove unused watches toRemove.forEach(function (watch, path) { diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6bd07c2fb8a4b..597a83adb319f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22451,7 +22451,7 @@ namespace ts { for (const decl of indexSymbol.declarations) { const declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - switch (declaration.parameters[0].type!.kind) { + switch (declaration.parameters[0].type.kind) { case SyntaxKind.StringKeyword: if (!seenStringIndexer) { seenStringIndexer = true; diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 773d0b8b8469f..d9fa8446b138b 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -367,7 +367,7 @@ namespace ts.JsDoc { const varStatement = commentOwner; const varDeclarations = varStatement.declarationList.declarations; const parameters = varDeclarations.length === 1 && varDeclarations[0].initializer - ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer!) + ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; return { commentOwner, parameters }; }